Sub topic 4
Membership Tests and Iteration
This chapter assumes you know basic Python syntax, how for loops and the in operator work, and the difference between mutable and immutable objects. You should also have seen how to create a set. Here you will learn how in behaves on sets, what "equal" means to a set, and what you can and cannot rely on when you loop over one.
Testing membership with `in`
A membership test asks whether a value is an element of a collection. For a set, the operator is in, and not in is its negation. Both return a bool.
allowed = {"read", "write", "exec"}
print("read" in allowed) # True
print("delete" in allowed) # False
print("delete" not in allowed) # TrueThe test needs no loop. Python goes straight to the place in the set where the value would be stored, so the cost does not grow with the size of the set. The last chapter section, below, explains why. For now, remember the practical rule: x in some_set takes about the same time for 10 elements as for 10 million.
The same test on a list compares x with each element in turn until it finds a match. A miss has to scan the whole list.
| Operation | `list` | `set` |
|---|---|---|
| `x in c`, value present | Scans until found, proportional to position | Constant time on average |
| `x in c`, value absent | Scans everything, proportional to length | Constant time on average |
| `c[0]` | Works | `TypeError`, sets have no positions |
| Iteration order | Insertion order, guaranteed | Arbitrary, do not rely on it |
You can check the difference yourself. The exact timings depend on your machine, so the program compares the two instead of printing them.
import timeit
data_list = list(range(100_000))
data_set = set(data_list)
list_time = timeit.timeit(lambda: 99_999 in data_list, number=100)
set_time = timeit.timeit(lambda: 99_999 in data_set, number=100)
print(set_time < list_time) # TrueLooking up the last element is the worst case for the list, which is why it makes a clear demonstration.
What "the same value" means to a set
A set decides that two values are the same using two checks: their hashes must match, and then the values must be equal with ==. Python also checks identity (is) first as a shortcut. This has consequences that surprise people.
Wait, the diagram must follow the required format. The diagram below shows the lookup steps.
Equal numbers collapse into one element
Numbers that compare equal also hash equally, so a set treats them as one value.
s = {1, 2, 3}
print(1.0 in s) # True, 1.0 == 1 and hash(1.0) == hash(1)
print(True in s) # True, True == 1
print("1" in s) # False, a string is never equal to an int
print(len({1, 1.0, True})) # 1When several equal values are added, the set keeps the first one it saw. This matters if you mix 1, 1.0 and True in one set. It usually means your data has a typing problem.
`nan` is a special case
float("nan") is not equal to itself, so nan == nan is False. Sets still find the exact same nan object because of the identity shortcut. A different nan object is not found.
nan = float("nan")
s = {nan}
print(nan in s) # True, the same object is found by identity
print(float("nan") in s) # False, a new nan is not equal to anythingIf you store nan values in a set, expect this behavior. Clean them out first, for example with math.isnan.
The value you look up must be hashable
Lookup computes hash(x), so the value you test must be hashable even when the answer would be False.
s = {1, 2}
try:
print([1, 2] in s)
except TypeError as e:
print(e) # unhashable type: 'list'There is one convenient exception. When you test a set for membership, Python quietly converts it to a frozenset for the lookup, so this works:
families = {frozenset({1, 2})}
print({1, 2} in families) # TrueFor any other unhashable type, such as a list or a dict, convert it to a tuple or frozenset before testing.
Iterating over a set
A for loop visits each element exactly once.
colors = {"red", "green", "blue"}
for color in colors:
print(color) # order is not specifiedThe order in which elements appear depends on their hashes and on the history of the set. You should treat it as arbitrary, for three reasons:
- String hashes are randomized for each Python process. The same program can print a set of strings in a different order on each run. You can fix this with the
PYTHONHASHSEEDenvironment variable, but you should not build code that needs it. - Small integers often come out looking sorted, because an int hashes to itself. That is an implementation detail, not a promise.
- Adding and removing elements can change the order of the ones that remain.
When you need a stable order, for example for printing, testing or writing a file, sort the elements.
colors = {"red", "green", "blue"}
for color in sorted(colors):
print(color) # blue, green, redsorted() returns a new list, so the set itself is unchanged. It needs the elements to be comparable with each other. A set that mixes int and str raises TypeError. Pass key=str or a more suitable key function if you must.
If you want to keep the original order and also remove duplicates, a set is the wrong tool for the order part. Use dict.fromkeys(items), which keeps first-seen order.
Other ways to read a set
A set has no positions, so s[0] raises TypeError: 'set' object is not subscriptable. These tools work with any iterable, and they all work on sets:
scores = {88, 92, 75, 92, 60}
print(len(scores)) # 4, the duplicate 92 was dropped
print(min(scores), max(scores)) # 60 92
print(sum(scores)) # 315
print(any(s < 65 for s in scores)) # True
print(all(s >= 60 for s in scores)) # True
first = next(iter(scores)) # one arbitrary element
print(first in scores) # Truenext(iter(s)) gives you some element without removing it. It raises StopIteration on an empty set, so give it a default, next(iter(s), None), when the set might be empty. Use s.pop() if you also want the element removed.
enumerate(s) works too, but the numbers it produces only count the elements. They are not stable positions, because the order is arbitrary.
Changing a set while looping over it
You cannot add or remove elements of a set while iterating over it. Python detects that the size changed 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 iterationThere are two safe patterns. The first loops over a copy and edits the original. The second builds a new set.
nums = {1, 2, 3, 4}
for n in list(nums): # the loop walks a copy
if n % 2 == 0:
nums.discard(n)
print(sorted(nums)) # [1, 3]
nums = {1, 2, 3, 4}
odds = {n for n in nums if n % 2} # a comprehension builds a new set
print(sorted(odds)) # [1, 3]The second form is usually clearer. Set comprehensions get their own chapter.
Choosing between a list and a set for lookups
Use a set when you test membership many times against the same group of values, and you do not need order or duplicates. Typical cases are allow lists, "seen so far" trackers and tag filters.
Stay with a list when you need order, duplicates or indexing, or when the collection is tiny and you only test it once. Building a set costs time and memory, so converting a list to a set pays off only when you reuse it.
banned = {"spam", "scam", "phish"}
messages = ["hello", "free spam", "meeting at 3"]
for msg in messages:
words = set(msg.split())
print(msg, "->", "blocked" if words & banned else "ok")Here words & banned is an intersection, covered in a later chapter. An empty set is falsy, so the conditional reads naturally.
Summary of edge cases
inuses the hash first, then identity or equality.- Values that are equal across types (
1,1.0,True) count as one element. - A
nanis found only by identity. - The tested value must be hashable, except that a
setis converted to afrozensetfor lookup. - Iteration order is arbitrary. Use
sorted()when order matters. - Do not change a set while you loop over it.
Exercise
What does this program print, and why? s = {1, 2, 3} followed by print(2.0 in s, "2" in s, [2] in s) would fail. Which of the three tests raises an error, and what two other results would be printed if you removed it?
Show answer
The test [2] in s raises TypeError: unhashable type: 'list', because a lookup must hash the value and lists are not hashable. Without it, 2.0 in s gives True, because 2.0 == 2 and both hash the same. "2" in s gives False, because a string is never equal to an int.
Exercise
You have tags = {"a", "b", "c", "d"} and want to remove every tag in tags that appears in the set drop = {"b", "d"} by looping over tags. Why does for t in tags: if t in drop: tags.remove(t) fail, and how would you fix it in one line using a comprehension?
Show answer
Removing from a set during iteration changes its size, so Python raises RuntimeError: Set changed size during iteration. A one-line fix is tags = {t for t in tags if t not in drop}. Looping over a copy with for t in list(tags) also works.