DEV Community

loading...

Python Enumerate

shyal profile image Shyal Beardsley ・1 min read

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)
Enter fullscreen mode Exit fullscreen mode

Output:

a
b
c
d
...
Enter fullscreen mode Exit fullscreen mode

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])
Enter fullscreen mode Exit fullscreen mode

Output:

0 a
1 b
2 c
3 d
...
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output:

0 a
1 b
2 c
3 d
...
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output:

1 a
2 b
3 c
4 d
...
Enter fullscreen mode Exit fullscreen mode

Discussion

pic
Editor guide