Sets and Membership
Unit ID: M03-U04 Estimated active time: 20-30 minutes
A set keeps unique values
raw_tags = ["python", "data", "python", "beginner"]
unique_tags = set(raw_tags)
print(unique_tags)
The duplicate "python" is removed. The displayed order may differ because sets are not sequence collections and should not be used when position matters.
Membership is direct
print("python" in unique_tags)
print("advanced" in unique_tags)
The results are True and False.
Add and remove
unique_tags.add("notebook")
unique_tags.discard("advanced")
add() inserts a value. discard() removes a value if present and does nothing if absent. remove() also removes a value but raises KeyError when absent.
Compare sets
required = {"python", "notebook"}
learner_skills = {"python", "notebook", "data"}
print(required.issubset(learner_skills))
print(learner_skills - required)
The subset check is True. The difference contains skills present in learner_skills but not in required.
Useful operations include:
- intersection with
&; - difference with
-; and - symmetric difference with
^.
Empty set reminder
empty_set = set()
empty_dictionary = {}
Use type() if the difference is unclear.
Set items must be hashable
Simple immutable values such as strings, numbers, and tuples of immutable values can normally be set items. A list cannot be a set item because it is mutable.
You do not need the internal hashing details yet. Remember the practical rule: use sets for unique stable values, not nested editable records.
Practice
Create two sets:
course_skills = {"python", "notebook", "data"}
learner_skills = {"python", "spreadsheets"}
Find the common skills, skills still needed for the course, and all unique skills across both sets. Explain why sorting the final values may help when displaying them to a person.
Takeaway
Sets answer uniqueness and membership questions. Do not rely on their order. Next, we will examine how mutable collections can share references and how to copy them deliberately.
