enumerate
Iterating with for in
In a variety of languages, especially c-based languages, iterating over lists, or arrays involves incrementing a variable until it reaches a certain size. Python for-loops actually lack this syntax, so for in
tend to get used a lot.
1 from string import ascii_lowercase as ascii
2
3 for c in ascii:
4 print(c)
Output:
1 a
2 b
3 c
4 d
5 ...
Iterating with indices
Thus what you end up doing to access a list via indices, is:
1 from string import ascii_lowercase as ascii
2
3 for i in range(len(ascii)):
4 print(i, ascii[i])
Output:
1 0 a
2 1 b
3 2 c
4 3 d
5 ...
Using enumerate
The pythontic way, when you want to access both the index and value directly, without the extra lookup, is to use enumerate
.
1 for i, c in enumerate(ascii):
2 print(i, c)
Output:
1 0 a
2 1 b
3 2 c
4 3 d
5 ...
Indexing from an arbirary number
If a second argument is passed into enumerate, it will begin indexing from that number. For example, to start indexing from 1
:
1 for i, c in enumerate(ascii, 1):
2 print(i, c)
Output:
1 1 a
2 2 b
3 3 c
4 4 d
5 ...