Sub topic 4
Membership Tests and Iteration
This chapter assumes you know Python's in operator, for loops, and the difference between mutable and immutable objects. It also assumes you have seen how to create a set. Here you will learn how in works on a set, what can go wrong with it, and what to expect when you loop over a set.
Testing membership with `in`
The in operator asks whether a value is one of the set's elements. It returns True or False.
allowed = {"read", "write", "admin"}
print("read" in allowed) # True
print("delete" in allowed) # False
print("delete" not in allowed) # TrueA set answers this question by hashing the value and jumping to the place where an equal element would be stored. A list has to compare the value against its items one by one. For large collections the difference is big.
| Collection | Cost of `x in collection` |
|---|---|
| list | proportional to length (scans items) |
| set | constant on average (hash lookup) |
Equality decides a match
The lookup uses both the hash and ==. Values that are equal and have equal hashes count as the same element, even when their types differ.
nums = {1, 2, 3}
print(1.0 in nums) # True, because 1 == 1.0 and their hashes match
print(True in nums) # True, because True == 1Unhashable values raise an error
The value you test must be hashable, just like the elements stored in the set.
tags = {"a", "b"}
try:
print([1, 2] in tags)
except TypeError as e:
print(e) # unhashable type: 'list'A list is not hashable, so Python cannot compute where to look and raises TypeError. A set is also unhashable, but there is one special case. When you test a set with in, Python quietly converts it to a temporary frozenset first.
groups = {frozenset({1, 2})}
print({1, 2} in groups) # TrueIterating over a set
A for loop visits each element once.
colors = {"red", "green", "blue"}
for color in sorted(colors):
print(color)
# blue
# green
# redA set has no defined order. The order you see can change between Python versions. For strings it can even change between runs, because Python randomizes string hashes at startup. Small integers often look sorted, but that is an implementation detail. If the output order matters, wrap the set in sorted(), as above.
Do not change a set while looping over it
Adding or removing elements during iteration invalidates the loop. Python detects the size change and raises RuntimeError.
nums = {1, 2, 3, 4}
try:
for n in nums:
if n % 2 == 0:
nums.remove(n)
except RuntimeError as e:
print(e) # Set changed size during iterationIterate over a copy instead, or build a new set.
nums = {1, 2, 3, 4}
for n in list(nums): # list(nums) is a snapshot
if n % 2 == 0:
nums.remove(n)
print(sorted(nums)) # [1, 3]
odds = {n for n in {1, 2, 3, 4} if n % 2 == 1}
print(sorted(odds)) # [1, 3]Other ways to consume a set
Functions that accept any iterable work on sets as well. Their results do not depend on order, except where noted.
scores = {70, 85, 92}
print(len(scores)) # 3
print(max(scores)) # 92
print(sum(scores)) # 247
print(any(s > 90 for s in scores)) # TrueIndexing does not work. scores[0] raises TypeError because a set has no positions. To get "some element", use next(iter(scores)), and treat the result as arbitrary.
Quick rules
- Use
inandnot inon a set for fast lookups. - The tested value must be hashable, apart from the set-to-frozenset special case.
- Equal values with equal hashes match, so
1,1.0andTruecollide. - Iteration order is arbitrary. Use
sorted()when order matters. - Never add or remove elements while looping. Loop over
list(s)or build a new set.
Exercise
The code for n in nums: if n > 2: nums.discard(n) raises RuntimeError on nums = {1, 2, 3, 4}. Why does it fail, and how do you fix it so that only 1 and 2 remain?
Show answer
The loop removes elements from the set it is iterating over, so the set's size changes mid-loop and Python raises RuntimeError. Loop over a snapshot with for n in list(nums): and discard inside it. You can also build a new set with {n for n in nums if n <= 2}. Either way the result is {1, 2}.