DEV Community

Cover image for Enumerate Python - Examples
Alex Tread
Alex Tread

Posted on • Originally published at pybuddy.com

Enumerate Python - Examples

We use for loops in a lot of cases in Python, but sometimes we need to get the current index of the current iterating element
inside the loop.

If we have a list like this in python:

languages = ['French', 'English', 'German', 'Chinese']
Enter fullscreen mode Exit fullscreen mode

We can get the index in different ways, for example:

index = 0
languages = ['French', 'English', 'German', 'Chinese']
for lang in languages:
    print(index, lang)
    index += 1
Enter fullscreen mode Exit fullscreen mode

It will print:

0 French
1 English
2 German
3 Chinese

Enter fullscreen mode Exit fullscreen mode

Or we can use something like this:

languages = ['French', 'English', 'German', 'Chinese']
for index in range(len(languages)):
    lang = languages[index]
    print(index, lang)
Enter fullscreen mode Exit fullscreen mode

But in Python, there is always a better way to do things right?

In this case, we use something called Enumerate in Python.

languages = ['French', 'English', 'German', 'Chinese']
for index, value in enumerate(languages):
    print(index, value)
Enter fullscreen mode Exit fullscreen mode

It will print:

0 French
1 English
2 German
3 Chinese
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
chemacortes profile image
Chema Cortés • Edited

This is a generic solution using enumerate(). But if you need an enumeration, you can also use the more specialized module enum:

from enum import Enum

languages = ['French', 'English', 'German', 'Chinese']
Languages = Enum("Languages", languages, start=0)

for lang in Languages:
    print(lang.value, lang.name)
Enter fullscreen mode Exit fullscreen mode