DEV Community

Cover image for Enumerate in Python

Posted on

Enumerate in Python

Are you new to Python? Did you program in other languages before?

You may think the way to get the index is by creating a loop, getting the size of the array, creating an index variable, comparing the index variable to the condition and increasing it manually.. phew!

In the C programming language you get something like this:

int i = 0;
for (i = 0; i <= 10; i++){
    printf("%s\n", list[i]);

Very cryptic right!

For loop index in Python

There is a Pythonic way to create loops with an index, namely enumerate().

for index, value in enumerate(some_list):
    print(index, value)

To give you a full example with a list:

my_list = ['apple', 'banana', 'grapes', 'pear']
for c, value in enumerate(my_list):
    print(c, value)

# Output:
# 0 apple
# 1 banana
# 2 grapes
# 3 pear

This works for numeric lists too:

>>> b = [3,6,7,2,9]
>>> for index, value in enumerate(b):
...     print(f"At b[{index}] the value is {value}")
At b[0] the value is 3
At b[1] the value is 6
At b[2] the value is 7
At b[3] the value is 2
At b[4] the value is 9

Great right! Syntax is very readable and Pythonic.

Related links:

Top comments (1)

mzaini30 profile image

I usually write like this:

for n, x in enumerate(data):

Because, in math, n is index of list 😂