A set is a mutable collection of unique, hashable values. Sets provide constant-time operations for insertion, removal, and membership testing. They are implemented using a hash table.
Key Characteristics:
- Construction: Use
set() for an empty set or set([iterable]) to create a set from an existing collection. There is no literal syntax. - Membership: Use
in and not in operators to check for presence. - Uniqueness: Duplicate elements are not stored.
- Ordering: Sets are iterable; the order of iteration follows the order in which elements were first added.
- Boolean Context: An empty set is
False; a non-empty set is True. - Comparison: Sets can be compared for equality (
==) and inequality (!=). Order of elements does not matter for equality. However, sets do not support ordered comparisons like <, <=, >, or >=.
s = set(["a", "b", "c"])
"a" in s # True
"z" in s # False
s = set(["z", "y", "z", "y"])
len(s) # 2
s.add("x")
len(s) # 3
for e in s:
print e # prints "z", "y", "x"