Set
A set in Python is an unordered collection data type that is iterable, mutable, and has no duplicate elements. Sets are useful for storing and performing operations on collections of unique elements.
Creating Sets
You can create a set using curly braces {} or by using the built-in set() constructor. However, creating an empty set requires the use of set(), as using {} creates an empty dictionary.
my_set = {1, 2, 3}
another_set = set([2, 3, 4])
empty_set = set()
Adding Elements
You can add an element to a set using the add method.
my_set.add(4) # my_set is now {1, 2, 3, 4}
Removing Elements
You can remove an element from a set using the remove or discard method. If the element is not present, remove will raise a KeyError, but discard will do nothing.
my_set.remove(1) # my_set is now {2, 3, 4}
my_set.discard(5) # Does nothing as 5 is not present in my_set
Set Operations
Sets support several mathematical operations such as:
Union
Combines the elements of two sets.
print(my_set | another_set) # or print(my_set.union(another_set))
Intersection
Finds the common elements between two sets.
print(my_set & another_set) # or print(my_set.intersection(another_set))
Difference
Finds the elements present in one set but not in the other.
print(my_set - another_set) # or print(my_set.difference(another_set))
Symmetric Difference
Finds the elements that are unique to each set.
print(my_set ^ another_set) # or print(my_set.symmetric_difference(another_set))
Iterating Over a Set
You can iterate over the elements of a set using a for loop.
for element in my_set:
print(element)
Checking Membership
You can check whether an element is in a set using the in keyword.
if 3 in my_set:
print('3 is in my_set')
Set Comprehension
Like lists and dictionaries, sets also support set comprehension to create new sets.
squared_set = {x*x for x in my_set}
print(squared_set) # Prints the squares of each element in my_set
Set Length
You can find the number of elements in a set using the len() function.
print(len(my_set))
Clearing a Set
You can remove all elements from a set using the clear() method.
my_set.clear() # my_set is now an empty set
Sets are particularly useful when you need to handle data where the order of elements doesn’t matter, and you need to ensure the elements are unique, like when working with sets in mathematics.