Sub topic 7
Finding items with in, index and count
Python gives you three built-in ways to ask a list questions about its contents. The in operator tells you whether a value is present. The index method tells you where the first match is. The count method tells you how many matches there are. This chapter assumes you can index and slice lists, write for loops and if statements, and call methods. It also assumes you know what None and exceptions are.
Testing membership with in
The in operator returns True if some item in the list equals the value, and False otherwise. The not in operator returns the opposite answer.
fruits = ["apple", "banana", "cherry", "banana"]
print("cherry" in fruits) # True
print("grape" in fruits) # False
print("grape" not in fruits) # True
if "apple" in fruits:
print("We have apples")Use in when you only need a yes or no answer. Write if x in items: rather than calling count or index and testing the result. It is shorter, it reads clearly, and it stops at the first match.
How equality is decided
in compares each item with the target from left to right. For each item, it first checks whether the two are the same object. If they are not, it checks item == target. It stops at the first match.
This has some consequences:
- Numbers compare by value across types, so
1,1.0andTrueall match each other. - For strings, the match must be exact.
"Apple" in ["apple"]isFalse. inlooks only at the top level. A value inside a nested list is not found.- Your own classes match by the rules of their
__eq__method.
print(1.0 in [1, 2, 3]) # True, because 1.0 == 1
print(True in [0, 1]) # True, because True == 1
print(2 in [[1, 2], [3, 4]]) # False, the items are lists
print([1, 2] in [[1, 2], [3, 4]]) # True, one item equals [1, 2]The identity check exists because of float("nan"), a "not a number" value that is not equal to itself. The same object is found, but a different NaN is not:
nan = float("nan")
print(nan == nan) # False
print(nan in [nan]) # True, same object
print(float("nan") in [nan]) # False, different objectYou will rarely meet this, but it explains why membership is not always the same as "some item == target".
Finding a position with index
list.index(x) returns the position of the first item equal to x. The match rules are the same as for in.
fruits = ["apple", "banana", "cherry", "banana"]
print(fruits.index("banana")) # 1
print(fruits.index("cherry")) # 2If the value is not in the list, index raises ValueError instead of returning something like -1. This is a deliberate design choice. A return value of -1 would be a valid negative index, so a careless caller could silently read the last item.
try:
fruits.index("grape")
except ValueError as error:
print(error) # 'grape' is not in listSearching part of the list
index takes optional start and stop arguments. They work like slice bounds: the search covers positions from start up to, but not including, stop. The result is still a position in the whole list, not in the searched part.
fruits = ["apple", "banana", "cherry", "banana"]
print(fruits.index("banana", 2)) # 3, search begins at position 2
print(fruits.index("banana", 0, 1)) # raises ValueError, only "apple" is searchedNegative values for start and stop count from the end, as in slicing.
Handling a missing value safely
There are two common ways to avoid a crash. The first checks before searching. The second catches the error.
def find_position(items, target):
"""Return the first position of target, or None if it is absent."""
try:
return items.index(target)
except ValueError:
return None
fruits = ["apple", "banana", "cherry"]
print(find_position(fruits, "cherry")) # 2
print(find_position(fruits, "grape")) # NoneChecking with if x in items: before calling items.index(x) also works, but it scans the list twice. Catching the exception scans once. Compare against None with is None, not with if not position, because a valid position of 0 is falsy.
position = find_position(fruits, "apple")
if position is not None:
print("found at", position) # found at 0Counting matches with count
list.count(x) returns the number of items equal to x. It always scans the whole list. It returns 0 when there are no matches and never raises an error.
fruits = ["apple", "banana", "cherry", "banana"]
print(fruits.count("banana")) # 2
print(fruits.count("grape")) # 0Because the same equality rules apply, [1, 1.0, True].count(1) is 3.
Do not use count as a membership test. items.count(x) > 0 is correct, but it scans the whole list even after finding a match, so x in items is both faster and clearer.
The three tools differ in what they return and when they stop:
| Tool | Returns | If no match | Stops scanning |
|---|---|---|---|
| `x in items` | `True` or `False` | `False` | At the first match |
| `items.index(x)` | Position of first match | Raises `ValueError` | At the first match |
| `items.count(x)` | Number of matches | `0` | Never, always scans all |
The diagram shows a way to choose between them.
Searching by a condition
in, index and count only test for equality with one value. To search by a rule, such as "the first number above 10", use a generator expression with the built-in functions any and next, or a comprehension.
nums = [4, 8, 15, 16, 23, 42]
print(any(n > 20 for n in nums)) # True
print(next((n for n in nums if n > 10), None)) # 15
print(sum(1 for n in nums if n % 2 == 0)) # 4 (how many are even)next(iterator, default) returns the first value the generator produces, or the default if it produces none. This is the usual replacement for index when the search is not an exact match.
Finding every position
index returns only the first match. To collect all positions, use enumerate, which pairs each item with its position.
def all_positions(items, target):
return [i for i, item in enumerate(items) if item == target]
fruits = ["apple", "banana", "cherry", "banana"]
print(all_positions(fruits, "banana")) # [1, 3]
print(all_positions(fruits, "grape")) # []An empty list for "no matches" is easier to handle than an exception, because a loop over it simply runs zero times.
Cost and when to switch structures
All three operations are linear. In the worst case, Python looks at every item, so the work grows in proportion to the list length. For a list of a few hundred items, you will not notice. For a large list that you test many times, the cost adds up: 10,000 lookups in a list of 100,000 items can mean up to a billion comparisons.
If you need frequent membership tests and you do not need the order, build a set once. Membership in a set takes roughly constant time because it uses hashing.
allowed = ["ann", "bo", "cy"]
allowed_set = set(allowed)
print("bo" in allowed_set) # True, fast even with millions of itemsA set requires hashable items, so a list of lists cannot be converted. It also drops duplicates and loses order. If you need positions, index is still the right tool. If you need counts for many different values, collections.Counter counts everything in a single pass.
from collections import Counter
counts = Counter(["apple", "banana", "cherry", "banana"])
print(counts["banana"]) # 2
print(counts["grape"]) # 0Common mistakes
- Expecting
indexto return-1for a missing value. It raises an exception. - Using
if items.index(x):as a membership test. It crashes when the value is absent and treats position0as false. - Assuming
insearches inside nested lists. It checks only the top-level items. - Calling
countorindexin a loop over the same list, which makes the total work quadratic. Build aCounteror a dictionary of positions first. - Forgetting that
True,1and1.0are equal, which makescount(1)include booleans.
Exercise
Given words = ["red", "blue", "red", "green", "red"], write code that prints the position of the second "red" without using a loop and without hard-coding the number 2 or 4. What does it print?
Show answer
Use the position of the first match as the start of a second search: first = words.index("red"); second = words.index("red", first + 1); print(second). It prints 2. The start argument makes the second search begin after the first match, so it finds the next one. If there were no second "red", the call would raise ValueError.
Exercise
Why is if "x" in items preferred over if items.count("x") > 0, and what would you use instead of either when you must test 50,000 different values against a list of 1,000,000 items?
Show answer
in stops at the first match, while count always scans the whole list, so in is faster and clearer. For the large workload, convert the list to a set once with set(items) and test each value against the set, because set membership takes roughly constant time instead of scanning the list every time.