Skip to content

Sets

In python, a set is a data structure that stores an unordered collection of unique elements. The elements of a set must be immutable and hashable, and cannot be repeated. Sets are useful for performing mathematical operations on sets, such as union, intersection and difference, and for removing duplicates from a list.

Let’s create some sets of fruits

set.py
# List of fruits
set1 = {'apple', 'banana', 'pear'}
set2 = {'pear', 'grape', 'mango'}
print(set1)
print(set2)

Output:

terminal
{'apple', 'banana', 'pear'}
{'pear', 'grape', 'mango'}

To add an element to a set, you can use the .add() method.

set.py
# List of fruits
set1 = {'apple', 'banana', 'pear'}
set2 = {'pear', 'grape', 'mango'}
# Add elements to a set
set1.add('strawberry')
set2.add('guava')
print(set1)
print(set2)

Output:

terminal
{'apple', 'banana', 'pear', 'strawberry'}
{'pear', 'grape', 'mango', 'guava'}

To delete an element from a set, you can use the .remove() method.

set.py
# List of fruits
set1 = {'apple', 'banana', 'pear'}
set2 = {'pear', 'grape', 'mango'}
# Delete elements from a set
set1.remove('pear')
set2.remove('mango')
print(set1)
print(set2)

Output:

terminal
{'apple', 'banana'}
{'pear', 'grape'}

You can join the elements of a set using the .union() function

set.py
# List of fruits
set1 = {'apple', 'banana', 'pear'}
set2 = {'pear', 'grape', 'mango'}
# Adding elements to a set
unions = set1.union(set2)
print(unions)

Output:

terminal
{'apple', 'banana', 'pear', 'grape', 'mango'}

You can extract the elements that are repeated between sets using the .intersection() function

set.py
# List of fruits
set1 = {'apple', 'banana', 'pear'}
set2 = {'pear', 'grape', 'mango'}
# Adding elements to a set
intersection = set1.intersection(set2)
print(intersection)

Output:

terminal
{'pear'}

You can obtain the elements that are in one set but not in another using the .difference() function. This is useful for identifying which values are exclusive to a set.

set.py
# List of fruits
set1 = {'apple', 'banana', 'pear'}
set2 = {'pear', 'grape', 'mango'}
# Adding elements to a set
difference = set1.difference(set2)
print(difference)

Output:

terminal
{'apple', 'banana'}
FunctionDescription
copy()Creates a copy of the set.
clear()Removes all elements from the set.
isdisjoint()Checks if two sets are disjoint (have no common elements).
issuperset()Checks if a set is a subset of another.
symmetric_difference()Returns the symmetric difference between two sets.
update()Modifies the original set by adding elements from another set.
intersection_update()Modifies the original set to contain only elements in common with another set.
difference_update()Modifies the original set to contain only elements that are not in another set.
symmetric_difference_update()Modifies the original set to contain only elements that are not in both sets.