Sets
In this tutorial, we'll store unique values and compare groups.
A set stores unique values. If you add the same value more than once, it only appears once.
tags = {"python", "beginner", "python"}
print(tags)
Output may be:
{'beginner', 'python'}
Sets do not keep a reliable order, so do not use them when positions matter.
Why Sets Are Useful
Sets are useful for uniqueness and membership checks:
allowed_users = {"ada", "grace", "linus"}
print("ada" in allowed_users)
print("sam" in allowed_users)
Output:
True
False
Adding and Removing
skills = {"Python", "HTML"}
skills.add("CSS")
skills.discard("HTML")
print(skills)
discard() is safe if the item is not there. remove() gives an error if the item is missing.
Set Operations
Sets can compare groups:
python_students = {"Ada", "Ben", "Cara"}
javascript_students = {"Ben", "Dan"}
print(python_students & javascript_students) # both
print(python_students | javascript_students) # either
print(python_students - javascript_students) # only Python
Common Mistake
This creates an empty dictionary, not an empty set:
empty = {}
Use:
empty_set = set()
When Not to Use a Set
Do not use a set if you care about the order of items or need duplicate values.
For example, scores in a game should probably be a list:
scores = [10, 10, 8, 6]
The repeated 10 matters. A set would remove the duplicate, which would change the meaning of the data.
Practice
Start with a list containing repeated names. Convert it to a set and print how many unique names there are.