set · Python
elem in s
Tests membership.
elem in s
Complexity
| Average | O(1) |
|---|---|
| Worst case | O(n) |
| Extra space | O(1) |
One hash and a short probe, instead of the O(n) scan `in` does on a list.
Tested example
words = {"apple", "pear"}
assert "apple" in words # hash, then ==
assert "Apple" not in words # no custom comparer: normalise the keys yourself
Parameters
- elem
- The element.
Behaviour
- Returns
- A bool.
- Errors and preconditions
- TypeError for an unhashable element (sets of sets need frozenset).
- Changes
- Nothing.
- Memory and invalidation
- No allocation.