Sub topic 5
Counting from 1 with the start argument
This chapter assumes you can write a for loop over a list, unpack a tuple in the loop header, and use enumerate to get an index and a value together. If for index, value in enumerate(items) looks unfamiliar, review the previous chapter first.
The default counter starts at 0
enumerate numbers items from 0 unless you say otherwise. That matches how Python indexes lists, so it works well when the number is used to look something up. It works badly when a person reads the number. People count tasks, steps, and lines from 1.
enumerate takes an optional second argument named start. It sets the number given to the first item.
tasks = ["write", "test", "ship"]
for number, task in enumerate(tasks, start=1):
print(f"{number}. {task}")Output:
1. write
2. test
3. shipEach later number is one more than the one before it. You can write start=1 or pass 1 positionally as enumerate(tasks, 1). The keyword form is easier to read, so prefer it.
What start changes and what it does not
start changes only the number in each pair. It does not change which items you get, and it does not skip anything. The signature is enumerate(iterable, start=0).
| Call | Pairs produced |
|---|---|
| `enumerate(["a", "b", "c"])` | `(0, 'a')`, `(1, 'b')`, `(2, 'c')` |
| `enumerate(["a", "b", "c"], start=1)` | `(1, 'a')`, `(2, 'b')`, `(3, 'c')` |
| `enumerate(["a", "b", "c"], start=10)` | `(10, 'a')`, `(11, 'b')`, `(12, 'c')` |
| `enumerate(["a", "b", "c"], start=-1)` | `(-1, 'a')`, `(0, 'b')`, `(1, 'c')` |
Any integer is allowed, including negative numbers and zero. The count always goes up by one.
Common error: using a 1-based number as an index
The most frequent mistake comes from mixing the two meanings of the number. With start=1, the counter is a label for people. It is no longer a valid position in the list.
tasks = ["write", "test", "ship"]
for number, task in enumerate(tasks, start=1):
print(number, tasks[number])This prints 1 test and 2 ship. Then it raises IndexError: list index out of range when number is 3, because the last valid index is 2. The first two lines are also wrong, since 1 is paired with "test" instead of "write".
The fix is to stop indexing. The loop already hands you the item, so use task:
for number, task in enumerate(tasks, start=1):
print(number, task)If you really need the position in the list, subtract one with tasks[number - 1]. Often that is a sign you should keep the default start=0 for the code and add 1 only when printing.
Common error: expecting start to skip items
Some learners read start=2 as "begin at the second item". It does not. It numbers the first item 2 and still visits every item.
tasks = ["write", "test", "ship"]
for number, task in enumerate(tasks, start=2):
print(number, task)Output:
2 write
3 test
4 shipTo skip items, slice the sequence first. Then choose a start that keeps the numbers honest:
for number, task in enumerate(tasks[1:], start=2):
print(f"{number}. {task}")This prints 2. test and 3. ship. The numbers match the original positions counted from 1. For iterators that cannot be sliced, such as an open file, use itertools.islice instead.
Common error: a non-integer start
start must be an integer. A float fails immediately, even when it looks whole.
try:
list(enumerate(["a", "b"], start=1.5))
except TypeError as error:
print(error)The message is 'float' object cannot be interpreted as an integer. If you need fractional or stepped numbering, compute it from the integer counter, for example number * 0.5.
A practical use: numbering a page of results
A useful start often comes from a calculation. When you show page 2 of a long list, the first item on that page is not number 1. It continues from the previous page.
items = ["a", "b", "c", "d", "e", "f", "g"]
page_size = 3
page = 2
offset = (page - 1) * page_size
page_items = items[offset:offset + page_size]
for number, item in enumerate(page_items, start=offset + 1):
print(f"{number}. {item}")Output:
4. d
5. e
6. fThe slice picks the right items, and start=offset + 1 makes their numbers match their place in the full list. The same idea numbers lines in a text file: pass the file object to enumerate with start=1, and the first line is line 1, as editors show it.
Summary of the rules
enumerate(iterable, start=n)makes the first counter valuen.- The counter increases by one for each item, and
ncan be any integer. startnever skips or reorders items.- A counter that starts at 1 cannot be used as a list index without subtracting 1.
Exercise
The code below should print a numbered list of the last two names, numbered 2 and 3, as they appear in the full list counted from 1. It currently prints the wrong output. Rewrite the loop so it prints "2. Grace" and "3. Linus". names = ["Ada", "Grace", "Linus"] for number, name in enumerate(names, start=2): print(f"{number}. {name}")
Show answer
The loop labels every name starting at 2, so it prints "2. Ada", "3. Grace", "4. Linus". start does not skip items. Slice off the first name and keep start=2:
names = ["Ada", "Grace", "Linus"]
for number, name in enumerate(names[1:], start=2):
print(f"{number}. {name}")
This prints "2. Grace" and "3. Linus".