Set
Like a list, a set holds a group of items. The difference is that a set only keeps unique items. It’s also unordered. The items won’t always come back in the order you added them.
Creating sets
To create an empty set, use the set() constructor.
bag = set()
print(bag)To start a set with values in it, use curly brackets. It looks like a dictionary. The difference is that you only write values, not key-value pairs.
# Duplicate elements, the set will make them unique!
bag = {"chapstick", "wallet", "chapstick"}
print(bag)Warning
You can’t create an empty set with curly brackets. Python treats {} as an empty dictionary.
Adding to a set
O(1)To add an item to a set, use the add() method.
bag = {"chapstick", "wallet", "keys"}
bag.add("sunglasses")
print(bag)Removing an item from a set
O(1)You can remove an item from a set in two ways:
remove()removes the item. It throws an error if the item isn’t there.discard()removes the item if it’s there. If it isn’t, nothing happens.
In interviews, we recommend using discard() so a missing item doesn’t crash your code. In real projects, it’s still good practice to handle errors properly.
bag = {"chapstick", "wallet", "keys"}
bag.remove("chapstick")
bag.discard("bamboo") # This will not throw an error.
print(bag)Checking if an object exists in a set
O(1)The main benefit of a set is that checking whether an item is in it takes constant time (O(1)). With a list, the same check takes O(n).
To check if an item is in a set, use the in operator.
bag = {"chapstick", "wallet", "keys"}
if "wallet" in bag:
print("My wallet is in the bag!")