Python supports many iterable objects: lists, tuples, and strings are just a few. Python’s for loop is flexible enough to handle these objects with ease. In particular, it saves you from dealing with the numeric index of each entry yourself.

But sometimes, you’ll want to work with an index, to count or filter items in a collection for example. Learn how you can use the Python enumerate function to iterate over a sequence while keeping track of both the index and the element.

Iterating Without enumerate()

Consider the following Python list.

        my_fruits = ["apples", "pears", "bananas"]

Suppose you want to keep track of the count of each element in the list. You could use a for loop with a range() function like this.

        count = 0
 
for fruit in range(len(my_fruits)):
    print(count, my_fruits[count])
    count += 1

While this works, it has a few shortcomings:

  • You have to keep track of the count outside the loop.
  • You have to increment the count in each iteration.
  • You have to calculate the length of the loop.
  • range(len()) only works with countable, indexable objects.

A better solution exists: the enumerate() function.

How enumerate() Works in Python

The Python enumerate() function takes a data collection and returns an enumerate object. The enumerate object contains a counter as a key for each item the object contains. The enumerate() function does so by assigning each item a count. This count corresponds to the number of iterations the function has completed to reach that value.

This counter makes it easier to access the items in the collection or even mutate the collection where possible.

With enumerate(), you do not have to keep track of the length of the loop or the iteration count. You can also avoid explicitly accessing the value using the index operator, like fruits[count]. The enumerate function automatically handles all these features.

The Syntax of Python enumerate()

Below is the general syntax for the enumerate() function.

        enumerate(iterable, start=0)

enumerate() takes two arguments:

  1. iterable: a data collection or sequence that Python can iterate over. E.g. a list or tuple.
  2. start: the index that the enumerate function should start counting from.

How enumerate() Is Implemented

To understand how enumerate() works, let’s see how it is actually implemented.

        def enumerate(sequence, start=0):
    n = start
 
    for elem in sequence:
        yield n, elem
        n += 1

This function, which you can find in the Python enumerate documentation, takes a sequence and a start argument which defaults to 0.

The function then initializes the n variable to the start variable. This keeps track of the number of iterations.

In the for loop that follows for each element in the sequence,

  • yield pauses the loop execution.
  • It also returns the current count (n), and value (elem).
  • When the loop resumes, it increments n.

The return value is an object of key-value pairs.

If you were to call the enumerate() function and pass it the list of fruits, this would be the output value.

        my_fruits = ["apples", "pears", "bananas"]
enumerate_object = enumerate(my_fruits)
print(list(enumerate_object))
 
# output - [(0, 'apples'), (1, 'pears'), (2, 'bananas')]

Enumerate With a Different Starting Index

In the above example, we did not specify the starting index. The example below shows you how you can set the starting index to a number of your choice.

To start at 10, do the following.

        enumerate_object = enumerate(my_fruits, 10)
print(list(enumerate_object))
 
# output - [(10, 'apples'), (11, 'pears'), (12, 'bananas')]

Python enumerate() Examples

Here are some examples showing how you can use enumerate() in Python.

Enumerate a Python String

In this example, you will use enumerate to retrieve the letter at index 5:

        my_string = "makeuseof"
 
for count, value in enumerate(my_string):
    if count == 5:
        print (value)
 
# output - s

Enumerate a Python Tuple

You can also use enumerate() to iterate over a Python tuple. In this example, the program prints a header in the first iteration, before displaying the items.

        my_fruits_tuple = ("apples", "pears", "bananas")
 
for index, value in enumerate(my_fruits_tuple):
    if (index == 0):
print("Fruits:")
 
    print(value)
 
/*
Fruits:
apples
pears
bananas
*/

Enumerate a Python List

In the example below, you are using enumerate to decrement all the numbers in the list above 10 by 2.

        my_number_list = [10, 17, 15, 6]
 
for index, value in enumerate(my_number_list):
    if (value > 10):
        my_number_list[index] -= 2
 
    print(my_number_list)
 
# output - [10, 15, 13, 6]

Use enumerate to Count Your Iterables

Python includes enumerate() as a built-in function. You can use it to iterate and count items in an iterable collection such as list, tuple, or string. It can help you keep track of the true index of each element, but you can also specify your own starting index. Use it as an alternative to the range() function if you are working with objects that are not countable and indexable objects.