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']
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
It will print:
0 French
1 English
2 German
3 Chinese
Or we can use something like this:
languages = ['French', 'English', 'German', 'Chinese']
for index in range(len(languages)):
lang = languages[index]
print(index, lang)
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)
It will print:
0 French
1 English
2 German
3 Chinese
Top comments (1)
This is a generic solution using
enumerate()
. But if you need an enumeration, you can also use the more specialized moduleenum
: