Learn with diagrams, code, systems and practical examples.
Sets
Track unique values and perform membership operations.
Sets are excellent when the question is whether a value has been seen or belongs to a group.
Start with the idea
A set stores unique hashable values. Membership checks are usually efficient, and set operations can combine or compare groups.
Small working example
Run this example first. Do not change several things at once; confirm the basic behavior, then experiment.
seen = {"a", "b"}
seen.add("a")
seen.add("c")
print("b" in seen)
print(len(seen)) A set stores unique hashable values. Membership checks are usually efficient, and set operations can combine or compare groups.
- Sets keep unique values.
- Membership is a core set operation.
- Sets do not model positional order.
True
3The example is intentionally small. Focus on the chapter’s main idea before adding extra syntax or framework code.
Common beginner mistake
Using a list for repeated membership checks when order and duplicates do not matter.
Use a set when uniqueness and membership are the real requirements.
Quick recap
- Sets keep unique values.
- Membership is a core set operation.
- Sets do not model positional order.
Try it yourself
These are deliberately small. If you can complete them without copying the example, you are ready to continue.
- Remove duplicates from sample input with a set.
- Find values common to two sets.