Lesson explanation
After this lesson, you will be able to:
A set stores unique values. Duplicate entries collapse into one element, so sets are useful for tags, permissions, and discovering which identifiers are missing. Sets do not have meaningful positions: never depend on iteration order or attempt to read items[0] from a set.
Use {value1, value2} to make a nonempty set and set() to make an empty one ({} creates an empty dictionary). add(value) inserts one value. discard(value) removes a value if present and does nothing if it is absent; unlike remove(value), it does not raise an error when missing.
Membership uses value in items. Set operations answer useful questions: a | b combines all unique values; a & b finds shared values; a - b keeps values present only in a. These operations return new sets rather than modifying the operands.
The repeated identifier counts as a single member.
regions = {"us", "eu", "us"}
print(len(regions))
print("eu" in regions)Output:
2
Truediscard() is safe even if the value is already missing.
roles = {"reader"}
roles.add("editor")
roles.discard("owner")
print(len(roles))
print("editor" in roles)Output:
2
TrueIntersection counts shared values; union counts everything present in either set.
online = {"api", "worker", "cache"}
monitored = {"cache", "mailer"}
print(len(online & monitored))
print(len(online | monitored))Output:
1
4Difference keeps the values that have not been granted.
required = {"read", "write", "deploy"}
granted = {"read", "deploy"}
print(len(required - granted))Output:
1| Need | Operation |
|---|---|
| Empty set | set() |
| Add one value | items.add(value) |
| Remove safely | items.discard(value) |
| Test membership | value in items |
| Combine unique items | `a |
| Shared items | a & b |
| Left-only items | a - b |
{} is an empty dictionary, not an empty set.append() belongs to lists, not sets.remove() raises KeyError for an absent element; use discard() when absence is acceptable.a - b is not the same as b - a.