Introduction to Python Sets
Python sets are an unordered collection of unique elements. They are widely used in Python programming due to their ability to efficiently perform mathematical set operations such as union, intersection, and difference. Sets in Python are mutable, which means that you can add or remove elements from them.
Creating a Set
To create a set in Python, you can use the set() function or enclose a sequence of elements within curly braces ({}):
my_set = set() my_set = {1, 2, 3}
Adding and Removing Elements
You can add elements to a set using the add() method:
my_set = {1, 2, 3} my_set.add(4)
To remove an element from a set, you can use the remove() or discard() method:
my_set = {1, 2, 3} my_set.remove(2) my_set.discard(3)
Set Operations
Python sets provide several operations that can be performed on sets:
Union
The union of two sets is a new set that contains all the unique elements from both sets. In Python, you can use the union() method or the “|” operator to perform the union operation:
set1 = {1, 2, 3} set2 = {3, 4, 5} union_set = set1.union(set2) # or union_set = set1 | set2
Intersection
The intersection of two sets is a new set that contains only the common elements between the two sets. In Python, you can use the intersection() method or the “&” operator to perform the intersection operation:
set1 = {1, 2, 3} set2 = {3, 4, 5} intersection_set = set1.intersection(set2) # or intersection_set = set1 & set2
Difference
The difference between two sets is a new set that contains the elements present in the first set but not in the second set. In Python, you can use the difference() method or the “-” operator to perform the difference operation:
set1 = {1, 2, 3} set2 = {3, 4, 5} difference_set = set1.difference(set2) # or difference_set = set1 - set2
Symmetric Difference
The symmetric difference between two sets is a new set that contains the elements that are present in either of the sets, but not in both. In Python, you can use the symmetric_difference() method or the “^” operator to perform the symmetric difference operation:
set1 = {1, 2, 3} set2 = {3, 4, 5} symmetric_difference_set = set1.symmetric_difference(set2) # or symmetric_difference_set = set1 ^ set2
Iterating over a Set
You can iterate over the elements of a set using a for loop:
my_set = {1, 2, 3} for element in my_set: print(element)
Membership Test
You can check if an element is present in a set using the “in” keyword:
my_set = {1, 2, 3} if 2 in my_set: print("2 is present in the set")
Conclusion
Python sets are a powerful data structure that allows you to efficiently store and manipulate unique elements. They provide various set operations such as union, intersection, difference, and symmetric difference. By understanding how to create, add, remove, and perform operations on sets, you can leverage the power of sets in your Python programs.