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.
from string import ascii_lowercase as ascii
for c in ascii:
print(c)
Output:
a
b
c
d
...
Iterating with indices
Thus what you end up doing to access a list via indices, is:
from string import ascii_lowercase as ascii
for i in range(len(ascii)):
print(i, ascii[i])
Output:
0 a
1 b
2 c
3 d
...
Using enumerate
The pythontic way, when you want to access both the index and value directly, without the extra lookup, is to use enumerate
.
for i, c in enumerate(ascii):
print(i, c)
Output:
0 a
1 b
2 c
3 d
...
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
:
for i, c in enumerate(ascii, 1):
print(i, c)
Output:
1 a
2 b
3 c
4 d
...
Top comments (0)