Set in Python
- Get link
- X
- Other Apps
Set in Python
In Python, a set is a collection of unique elements. This means that there are no duplicate values in a set. Sets are useful for removing duplicates, performing mathematical operations such as union and intersection, and testing for membership. In this blog, we will explore how to create sets, add elements to sets, and perform operations on sets in Python.
Creating a Set
To create a set in Python, you can use the built-in set() function or enclose a list of elements in curly braces {}. Here are some examples:
# creating a set using the set() function my_set = set(['apple', 'banana', 'cherry']) # creating a set using curly braces my_set = {'apple', 'banana', 'cherry'}
Adding Elements to a Set
You can add elements to a set using the add() method or the update() method. The add() method adds a single element to the set, while the update() method adds multiple elements to the set.
my_set = {'apple', 'banana', 'cherry'} my_set.add('orange') print(my_set) # output: {'apple', 'banana', 'cherry', 'orange'} my_set.update(['mango', 'pineapple']) print(my_set) # output: {'apple', 'banana', 'cherry', 'orange', 'mango', 'pineapple'}
Removing Elements from a Set
You can remove elements from a set using the remove() method or the discard() method. The remove() method removes a specific element from the set, while the discard() method removes an element if it exists in the set, but does not raise an error if the element is not found.
my_set = {'apple', 'banana', 'cherry'} my_set.remove('banana') print(my_set) # output: {'apple', 'cherry'} my_set.discard('orange') print(my_set) # output: {'apple', 'cherry'}
Updating Elements in a Set
In this example, we first remove the element 'banana' from the set using the remove() method. Then, we add the new element 'mango' to the set using the add() method. The resulting set contains the elements 'apple', 'cherry', and 'mango'.
Note that if you try to remove an element that does not exist in the set using the remove() method, it will raise a KeyError exception. To avoid this, you can use the discard() method instead, which removes an element if it exists in the set but does not raise an error if the element is not found. Here's an example:
my_set = {'apple', 'banana', 'cherry'} print(my_set) # output: {'apple', 'banana', 'cherry'} # removing 'orange' from the set using the discard() method my_set.discard('orange') print(my_set) # output: {'apple', 'banana', 'cherry'}
discard() method instead of the remove() method, no error is raised and the set remains unchanged.- Get link
- X
- Other Apps
Comments