Sets are unordered collections of unique objects. A set cannot store two equal objects. This makes them particularly useful for removing duplicates from collections of items.
Since sets do not maintain any particular order, you cannot access items via an index (like with lists or tuples). However, you can iterate over them, and checking if a set contains a particular item is very efficient.
fruits = {"orange", "apple", "banana"}
print(fruits)
# Add items
fruits.add("mango")
fruits.add("orange")
# Note that "orange" has not been added twice.
print(fruits)
# Remove an item
fruits.remove("apple")
print(fruits)
# Iterate over the set
for fruit in fruits:
print(fruit)
# Check if an item is in a set
print("apple" in fruits)
print("mango" in fruits)
{'orange', 'apple', 'banana'}
{'orange', 'apple', 'mango', 'banana'}
{'orange', 'mango', 'banana'}
orange
mango
banana
False
True
Union and Intersection
Python sets have various special set-related methods. In particular you can obtain the union of two sets (the set of items contained in either or both of the sets) and the intersection of two sets (the set of items that are present in both sets).
colors = {"red", "green", "orange"}
fruits = {"orange", "apple", "banana"}
print(colors)
print(fruits)
intersection = colors.intersection(fruits)
union = colors.union(fruits)
print("Intersection: ", intersection)
print("Union: ", union)
{'red', 'orange', 'green'}
{'banana', 'apple', 'orange'}
Intersection: {'orange'}
Union: {'banana', 'orange', 'apple', 'green', 'red'}
Leave a Reply