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.

Example

languages = ["PHP", "Python", "Java", "JavaScript"]

for lang in languages:
  print lang

# Prints out:
# PHP
# Python
# Java
# JavaScript

for index, lang in enumerate(languages):
  print index, lang

# Prints out:
# 0 PHP
# 1 Python
# 2 Java
# 3 JavaScript

Although you can’t access the tuples directly you could think of an enumerate object to just be a list of tuples:

languages = ["PHP", "Python", "Java", "JavaScript"]

enumerate(languages)
# (0, PHP)
# (1, Python)
# (2, Java)
# (3, JavaScript)

You can also set the starting number that is added to the tuples as a separate argument to the Python enumerate function:

languages = ["PHP", "Python", "Java", "JavaScript"]

for index,lang in enumerate(languages, start=1):
  print index, lang

# Prints out:
# 1 PHP
# 2 Python
# 3 Java
# 4 JavaScript

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.

languages = ["PHP", "Python", "Java", "JavaScript"]
for index in range(len(languages)):
  print index+1, languages[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.

languages = ["PHP", "Python", "Java", "JavaScript"]

languages.next()
# (0, "PHP")

languages.next()
# (0, "Python")

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.

Conclusion

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.