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

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more