Sub topic 5
Counting from 1 with the start argument
This chapter covers the start argument of enumerate. You should already be comfortable with for loops over lists, tuple unpacking in a loop header (for a, b in pairs), and the basic form for index, value in enumerate(seq). If any of those are shaky, review the earlier chapters on them first.
By the end you will know what start does and what it doesn't do. You will also know when it fits, and which mistakes it makes easy.
What start changes
enumerate has this signature:
enumerate(iterable, start=0)The counter begins at start and goes up by one for every item. The items themselves are untouched, and so is their order. Only the number attached to each item changes.
fruits = ["apple", "banana", "cherry"]
print(list(enumerate(fruits)))
# [(0, 'apple'), (1, 'banana'), (2, 'cherry')]
print(list(enumerate(fruits, start=1)))
# [(1, 'apple'), (2, 'banana'), (3, 'cherry')]
print(list(enumerate(fruits, 1)))
# [(1, 'apple'), (2, 'banana'), (3, 'cherry')]The second and third calls give the same result. start can be passed by position or by keyword. Prefer the keyword form, start=1. A bare 1 in enumerate(fruits, 1) makes the reader stop and recall what the second parameter means.
Here is the shape of the idea. The pairs are produced from the iterable, and start only decides the first number.
start does not skip items
A common misreading is that start=1 means "begin at the second item". It does not. Every item is still produced. Compare it with slicing, which does remove items:
fruits = ["apple", "banana", "cherry"]
print(list(enumerate(fruits, start=1)))
# [(1, 'apple'), (2, 'banana'), (3, 'cherry')]
print(list(enumerate(fruits[1:])))
# [(0, 'banana'), (1, 'cherry')]
print(list(enumerate(fruits[1:], start=1)))
# [(1, 'banana'), (2, 'cherry')]The first call keeps all three fruits and labels them from 1. The second drops apple and then labels the rest from 0. The third drops apple and labels from 1. The two choices are independent: slicing decides which items you see, and start decides how they are numbered.
The same independence holds for the source. start works with any iterable, including strings, tuples, dictionaries, generators and open files. The counter is separate from the data.
Why start=1 exists
Python counts from 0 because indexes measure the offset from the first element. People count from 1. Whenever a number is shown to a person, such as a step, a rank, a line or a row, 1-based numbering usually fits better.
Before start, programmers wrote one of two awkward things:
tasks = ["write", "test", "ship"]
# Adding 1 at every use
for index, task in enumerate(tasks):
print(f"{index + 1}. {task}")
# A manual counter
number = 1
for task in tasks:
print(f"{number}. {task}")
number += 1Both work. The first scatters + 1 through the loop body, and every place that uses the number must remember to add it. The second brings back the manual counter that enumerate was meant to remove. With start, the loop header states the numbering once:
tasks = ["write", "test", "ship"]
for number, task in enumerate(tasks, start=1):
print(f"{number}. {task}")1. write
2. test
3. shipFormatting the counter
The counter is an ordinary int, so format specifications apply. Zero-padding or right-aligning keeps columns tidy when the list grows past nine items:
steps = ["mix", "pour", "bake"]
for number, step in enumerate(steps, start=1):
print(f"{number:02d}. {step}")01. mix
02. pour
03. bakeLine numbers in text
Text editors, compilers and error messages all number lines from 1. When you report a problem in a file, start=1 makes your numbers match what the user sees in their editor. A file object is an iterable of lines, so it works directly. This example uses io.StringIO so it runs without an external file:
import io
text = io.StringIO("first line\nsecond line\n\nfourth line\n")
for line_number, line in enumerate(text, start=1):
if line.strip() == "":
print(f"line {line_number} is blank")line 3 is blankWith the default of 0, this would report line 2, which would send the user to the wrong place.
Using start as an offset
start is not limited to 0 and 1. Any integer works, so you can use it to continue numbering from somewhere else. Pagination is a typical case. Page 2 of a list with three items per page should show items 4, 5 and 6, not 1, 2 and 3 again.
def show_page(items, page, per_page=3):
first = (page - 1) * per_page
chunk = items[first:first + per_page]
for rank, item in enumerate(chunk, start=first + 1):
print(f"{rank}. {item}")
animals = ["ant", "bee", "cat", "dog", "eel", "fox", "gnu"]
show_page(animals, 1)
show_page(animals, 2)1. ant
2. bee
3. cat
4. dog
5. eel
6. foxHere the slice picks the items and start=first + 1 picks the numbers. Because the two are independent, the labels stay consistent with the full list.
Negative values are legal too. They are useful when the first item is a header that should not count:
rows = ["header", "alice", "bob"]
for row_number, row in enumerate(rows, start=-1):
print(row_number, row)-1 header
0 alice
1 bobThis is rare, and a reader may need a moment to understand it. Use it only when the numbering has a clear meaning. A short comment helps.
Choosing a start value
| Situation | Typical `start` | Reason |
|---|---|---|
| Using the number as an index into the same list | `0` (default) | The counter matches the list position |
| Showing a numbered list to a person | `1` | People count from 1 |
| Reporting line numbers in a file | `1` | Editors number lines from 1 |
| Continuing numbering on a later page or batch | `offset + 1` | The labels follow the full sequence |
| Skipping a header row in the numbering | `-1` or `0` | The header gets a different label from the data |
What the counter really is
enumerate is lazy. It does not build a list of pairs. It wraps your iterable, and each time the loop asks for the next item it pulls one value from the source and attaches the current counter. This function is a close model of the behavior:
def my_enumerate(iterable, start=0):
number = start
for item in iterable:
yield number, item
number += 1
fruits = ["apple", "banana", "cherry"]
print(list(my_enumerate(fruits, start=1)) == list(enumerate(fruits, start=1)))
# TrueTwo consequences follow. First, start is only read once, when the counter is created, so changing a variable afterward has no effect on a running loop. Second, because the result is an iterator, it can be consumed only once. That pitfall gets its own chapter later in the tutorial.
Common errors
Using the 1-based counter as a list index
This is the most frequent bug with start=1. The number is a label. It is no longer a valid position in the list, so indexing with it is off by one:
tasks = ["write", "test", "ship"]
try:
for number, task in enumerate(tasks, start=1):
print(number, tasks[number])
except IndexError:
print("IndexError: tasks[3] does not exist")1 test
2 ship
IndexError: tasks[3] does not existThe output also shows the quieter half of the bug. The first two lines are paired with the wrong tasks, and no error warns you. Only the last iteration fails.
The fix is to use the value the loop already gives you:
tasks = ["write", "test", "ship"]
for number, task in enumerate(tasks, start=1):
print(number, task)If you really need both a position and a display number, the default start=0 with index + 1 for display is clearer, because only one of the two values is ever used as an index.
Passing a non-integer
The counter must be an integer. Floats and strings raise TypeError when enumerate is created, so you find out immediately:
fruits = ["apple", "banana", "cherry"]
for bad_start in (1.5, "1"):
try:
list(enumerate(fruits, start=bad_start))
except TypeError:
print(f"start={bad_start!r} is not an integer")start=1.5 is not an integer
start='1' is not an integerThis matters when the start value comes from user input or a config file. Convert it with int(...) first.
Swapping the arguments
The iterable comes first and start second. enumerate(1, fruits) fails because 1 is not iterable. The keyword form guards against this, since enumerate(fruits, start=1) can't be confused with the reverse.
Unpacking in the wrong order
enumerate yields (number, item), with the number first. Writing for task, number in enumerate(tasks, start=1) does not fail. It gives task the integer and number the string, and the output looks wrong in a confusing way. If numbers show up where names should be, check the order in the loop header.
Trusting the counter after the loop
Code sometimes uses the loop variable after the loop to find the number of items. With start=1, the last value of the counter equals the item count, but only if the loop ran at least once:
items = []
for count, item in enumerate(items, start=1):
print(count, item)
try:
print(count)
except NameError:
print("the loop never ran, so count was never defined")the loop never ran, so count was never definedIf you want the count, give the variable a safe initial value before the loop. For start=1, the value 0 is both correct and natural:
items = ["a", "b"]
count = 0
for count, item in enumerate(items, start=1):
print(count, item)
print(f"{count} item(s)")1 a
2 b
2 item(s)This works only when start=1. For any other start value, use len(items), which is simpler. Relying on a loop variable that outlives its loop is fragile in any case, so compute the count directly when it matters.
When to use enumerate with start, and when not to
Use enumerate(seq, start=1) when the number is shown to people or has to match a 1-based external system such as an editor, a spreadsheet row, a database page or a ticket list.
Don't reach for start when the number is an index into the same sequence. A different start then introduces the off-by-one bug described above. Don't use it either when you want to skip items. Slice the sequence or use itertools.islice. Don't use it when you need a step other than 1. enumerate always adds exactly one, so for other steps you would multiply, as in number * 10, or use a different tool.
Summary
enumerate(iterable, start=0)begins its counter atstartand adds one per item.startchanges labels only. It never skips, reorders or removes items.- Use
start=1for numbers a person reads, and prefer the keyword form. - Any integer is allowed, including offsets and negatives. Floats and strings raise
TypeError. - With
start=1, don't use the counter as a list index. Use the item variable. - Like the default form, the result is a lazy, one-shot iterator.
Exercise
What does this code print, and what would it print if start=1 were removed?
items = ["x", "y", "z"]
for n, item in enumerate(items[1:], start=1):
print(n, item)
Show answer
It prints "1 y" and then "2 z". The slice items[1:] removes "x" before enumerate sees the list, and start=1 numbers the remaining two items from 1. Without start=1 the output would be "0 y" and "1 z".
Exercise
A loop prints a numbered menu with enumerate(options, start=1). The user types a number, and the code then reads options[choice]. Why is this wrong, and how do you fix it?
Show answer
The menu numbers are 1-based, but list positions are 0-based, so options[choice] returns the item after the one the user chose, and raises IndexError if they chose the last entry. Fix it by looking up options[choice - 1] after checking that 1 <= choice <= len(options). Alternatively, build a dict with dict(enumerate(options, start=1)) and look up the item by choice.
Exercise
Write a function numbered(lines, first=1) that returns a list of strings like "7: text", where the numbering starts at the value of first. Then give the result of numbered(["a", "b"], first=7).
Show answer
def numbered(lines, first=1): return [f"{number}: {line}" for number, line in enumerate(lines, start=first)] numbered(["a", "b"], first=7) returns ["7: a", "8: b"].