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.
1from string import ascii_lowercase as ascii
2
3for c in ascii:
4 print(c)
Output:
1a
2b
3c
4d
5...
Iterating with indices
Thus what you end up doing to access a list via indices, is:
1from string import ascii_lowercase as ascii
2
3for i in range(len(ascii)):
4 print(i, ascii[i])
Output:
10 a
21 b
32 c
43 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
.
1for i, c in enumerate(ascii):
2 print(i, c)
Output:
10 a
21 b
32 c
43 d
5...
Indexing from an arbitrary number
If a second argument is passed into enumerate, it will begin indexing from that number. For example, to start indexing from 1
:
1for i, c in enumerate(ascii, 1):
2 print(i, c)
Output:
11 a
22 b
33 c
44 d
5...