Set
Set
Using add()
1 my_set = {1, 2, 3}
2 my_set.add(4)
Using update()
1 my_set = {1, 2, 3}
2 my_set.update([3, 4, 5])
Removing Elements from a Set
To remove elements from a set, you can use the remove(), discard(), or pop()
methods.
Using remove()
1 my_set = {1, 2, 3, 4}
2 my_set.remove(3)
Using discard()
1 my_set = {1, 2, 3, 4}
2 my_set.discard(5) # No error if element not present
Using pop()
1 my_set = {1, 2, 3, 4}
2 popped_element = my_set.pop() # Removes and returns an arbitrary element
Set Operations
Sets support various mathematical operations like union, intersection, difference,
and symmetric difference.
Union
1 set1 = {1, 2, 3}
2 set2 = {3, 4, 5}
3 union_set = set1.union(set2)
4 # or simply
5 union_set = set1 | set2
Intersection
1 set1 = {1, 2, 3}
2 set2 = {3, 4, 5}
3 intersection_set = set1.intersection(set2)
4 # or simply
5 intersection_set = set1 & set2
Difference
1 set1 = {1, 2, 3}
2 set2 = {3, 4, 5}
3 difference_set = set1.difference(set2)
4 # or simply
5 difference_set = set1 - set2
Symmetric Difference
1 set1 = {1, 2, 3}
2 set2 = {3, 4, 5}
3 symmetric_difference_set = set1.symmetric_difference(set2)
4 # or simply
5 symmetric_difference_set = set1 ^ set2
Set Membership Test and Subset/Superset Test
You can check if an element exists in a set using the in keyword. To test if a set
is a subset or superset of another, use the issubset() and issuperset() methods,
respectively.
Code
script.py
1
2
3
4
5
6
7
8
9
10
my_set = {1, 2, 3, 4, 5}
set1 = {1, 2}
set2 = {1, 2, 3, 4, 5}
Execute code
Converting Lists to Sets and Sets to Lists
You can convert a list to a set and vice versa using the set() and list()
functions.
Code
script.py
1
2
3
4
5
6
7
# Converting a list to a set
my_list = [1, 2, 3, 3, 4, 5]
my_set = set(my_list)
Execute code
Common Use Cases for Sets
Sets are widely used in various scenarios, including:
Eliminating Duplicates: Since sets only store unique elements, you can use them to
remove duplicates from a list.
Membership Testing: Sets provide fast membership tests, making it efficient to
check if an element exists in a collection.
Finding Common Elements: Set intersection can be used to find common elements
between multiple sets.
Conclusion
Sets are a powerful data structure in Python that provide unique element storage
and support efficient mathematical set operations. They are versatile and find
applications in a wide range of scenarios, from data processing to set-based
computations. Understanding sets and their operations can significantly improve the
efficiency and readability of your Python code.