Sub topic 7
Finding items with in, index and count
This chapter assumes you can create lists, read items by index, and write for loops and if statements. You will learn three tools for searching a list: the in operator, the index method and the count method.
Checking membership with in
The in operator answers one question: is this value somewhere in the list? It returns True or False. Use not in for the opposite test.
colors = ["red", "green", "blue"]
print("green" in colors) # True
print("purple" in colors) # False
print("purple" not in colors) # TruePython compares each item to your value with ==, starting at the front. It stops at the first match. If there is no match, it checks every item. The comparison is by equality, so 1 in [1.0, 2.0] is True because 1 == 1.0.
Finding a position with index
list.index(value) returns the position of the first item equal to value. If the value is missing, it raises ValueError.
colors = ["red", "green", "blue", "green"]
print(colors.index("green")) # 1The result is the first match only. The second "green" at position 3 is ignored. You can pass optional start and stop arguments to search part of the list. This finds the second one:
colors = ["red", "green", "blue", "green"]
print(colors.index("green", 2)) # 3Avoiding ValueError
The most common error is calling index on a value that might be absent. Guard the call with in, or catch the exception.
colors = ["red", "green", "blue"]
target = "purple"
if target in colors:
print(colors.index(target))
else:
print(f"{target} not found")
try:
position = colors.index(target)
except ValueError:
position = -1
print(position) # -1The in check scans the list, and then index scans it again. For a long list, try/except does the work in one pass.
Counting matches with count
list.count(value) returns how many items equal value. It returns 0 when there are none, and it never raises an error.
votes = ["yes", "no", "yes", "yes", "no"]
print(votes.count("yes")) # 3
print(votes.count("maybe")) # 0Because count returns 0 for a missing value, votes.count("maybe") > 0 works as a membership test. It is slower than in, though, because it always reads the whole list. in stops at the first match.
How the three tools differ
| Tool | Returns | If the value is missing | Stops at first match |
|---|---|---|---|
| `value in lst` | `True` or `False` | `False` | Yes |
| `lst.index(value)` | Position of first match | Raises `ValueError` | Yes |
| `lst.count(value)` | Number of matches | `0` | No |
Searching by a condition
These tools only test equality with a given value. To search by a rule, such as "the first number above 10", use a loop or a generator expression with next.
numbers = [4, 8, 15, 16, 23, 42]
first_big = next((n for n in numbers if n > 10), None)
print(first_big) # 15The second argument to next is the default returned when nothing matches, so no exception is raised.
Exercise
Given letters = ["a", "b", "a", "c", "a"], what do letters.count("a"), letters.index("a", 1) and "d" in letters return?
Show answer
letters.count("a") returns 3, because "a" appears three times. letters.index("a", 1) returns 2, because the search starts at position 1 and the next "a" is at position 2. "d" in letters returns False, because "d" is not in the list.
Exercise
Write a function safe_index(items, value) that returns the position of value in items, or -1 if it is not present, without calling in first.
Show answer
def safe_index(items, value): try: return items.index(value) except ValueError: return -1