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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

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

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay