Last updated on
In this HowTo i’ll explain how the Python enumerate functions works.
What is the Python enumerate function?
The Python enumerate function is a built in function that returns an enumerate object.
So what is an enumerate object exactly?
Well, it stores all of the data that you had in your list but puts it in to tuples that can a number followed by the item in the list.
Although you can’t access the tuples directly you could think of an enumerate object to just be a list of tuples:
You can also set the starting number that is added to the tuples as a separate argument to the Python enumerate function:
You can also just provide the starting number directly as an argument:
for index,lang in enumerate(languages, 1): print index, lang
When might you use the Python enumerate function?
Probably a good example of when you might use the Python enumerate function is when you are using a for loop and want to keep track of the index.
As with the examples above you could do the same thing with enumerate and achieve the same as with range. Using the Python enumerate function is arguably a bit neater.
Another time you might want to use enumerate is when you want to manually move to the next tuple rather than relying on a for loop.
An enumerate object can make use of the next() method to get the next tuple.
This might be useful if you are testing the values in the tuples and only want to get the next one if a condition is met.
Whilst not amazingly different from looping through a list, using enumerate will allow you to access an index of each item. This is stored in an object however and isn’t directly accessible.
You can use enumerate to add an index to an existing list when you loop through it.