How to start enumerate() at 1 in Python
In Python, the built-in function enumerate()
allows you to get both the element and index (count) from iterable objects, such as list
and tuple
, within a for
loop. You can start the index at any value.
The sample code in this article uses the following list as an example.
l = ['Alice', 'Bob', 'Charlie']
See the following articles for more information about for
loop and how to use enumerate()
and zip()
together.
How to use enumerate()
Normal for
loop
for name in l:
print(name)
# Alice
# Bob
# Charlie
for
loop with enumerate()
By passing an iterable object to enumerate()
, you can get index, element
.
for i, name in enumerate(l):
print(i, name)
# 0 Alice
# 1 Bob
# 2 Charlie
Start index at 1 with enumerate()
As demonstrated in the example above, the index of enumerate()
starts at 0
by default.
If you want to start with a different number, pass that number as the second argument to enumerate()
.
Start at 1:
for i, name in enumerate(l, 1):
print(i, name)
# 1 Alice
# 2 Bob
# 3 Charlie
Start at the other number:
for i, name in enumerate(l, 42):
print(i, name)
# 42 Alice
# 43 Bob
# 44 Charlie
For example, this approach is useful when generating sequential number strings beginning from 1. Passing the starting number as the second argument to enumerate()
is more efficient than calculating i + 1
.
for i, name in enumerate(l, 1):
print(f'{i:03}_{name}')
# 001_Alice
# 002_Bob
# 003_Charlie
See the following article for f-strings used for zero-padding.
Set step with enumerate()
There is no argument like step
to specify increment to enumerate()
, but it can be done as follows.
step = 3
for i, name in enumerate(l):
print(i * step, name)
# 0 Alice
# 3 Bob
# 6 Charlie