dict · Python
key in d
Tests whether a key is present. Values are not indexed.
key in d; value in d.values()
Complexity
| Average | O(1) for keys |
|---|---|
| Worst case | O(n) for values (always a scan) |
| Extra space | O(1) |
Keys go through the hash table; d.values() is just a view to iterate.
Tested example
ages = {"ada": 36}
assert "ada" in ages # tests keys, by hash then ==
assert 36 not in ages # values are not searched
assert 36 in ages.values() # that scan is O(n)
Parameters
- key
- The key.
Behaviour
- Returns
- A bool.
- Errors and preconditions
- TypeError for an unhashable key.
- Changes
- Nothing.
- Memory and invalidation
- No allocation.