Python Enumerate: An Explanation With Examples

by | Python

Working with lists and other iterable objects is a common task in Python programming. At times, you may need to loop through these iterables while also keeping track of the index or count of the current element. That’s where Python’s built-in enumerate() function comes to the rescue.

The enumerate() function in Python provides you with a convenient way to access both the index of an item and the item itself when you’re looping over a list, or any iterable object.

Python Enumerate

This function makes your code more Pythonic, readable, and efficient. It allows you to loop through elements and retrieve both their index and value. Instead of manually initializing and incrementing a counter within the loop, you can rely on enumerate() to do the job for you.

In this article, you’ll learn about Python’s built-in function enumerate() function, its importance in your Python code, and its use cases.

Let’s get into it!

What is Python Enumerate Function?

Imagine you’re working with a list data structure and you want to do something with each item, but you also need to know the position of the item in the list.

Without Python enumerate(), you might decide to use a counter variable that you increment in every loop iteration. But this approach could be prone to errors and it’s not very “Pythonic.”

Enumerate is a built-in function in Python that enables you to iterate over iterable objects while keeping track of the index of the current item.

Now that you’ve understood what the enumerate() function in Python is, let’s move on to the syntax of the Python enumerate() function in the next section!

What is the Syntax of Python Enumerate Function?

The syntax of a function defines how you should use that function in your code, including what arguments it takes and what it returns.

Syntax of Python Enumerate Function

The enumerate() function takes the following syntax:

enumerate(<iterable>, start=0)
  • <iterable>: This is a required parameter and can be any Python iterable, such as a list or tuple.

  • start: This second parameter is an optional parameter that specifies the starting value of the counter. By default, it is set to 0.

The enumerate() function’s return value is an enumerate object, which is an iterator having pairs of (index, element) for each item in the given iterable.

You can use this iterator in a for loop to access both the index and the item simultaneously.

The following example shows how you can use enumerate() function with a list:

fruits = ['apple', 'banana', 'cherry']

for index, item in enumerate(fruits):
    print(index, item)

In this example, enumerate() loops through the enumerate objects, i.e., the fruits list, and assigns an index to each item, starting from 0.

The for loop then unpacks the index and item from the enumerated object. This enables you to perform operations based on both the index and the item’s value.

We are using the print function to print the index and the item to the screen. The output of the code is given in the image below:

Printing the index value pairs with enumerate and for loop

In the output, you can see that the starting index is 0. This is the default value of the index assigned automatically by the Python interpreter.

However, you can also specify a different starting value for the counter by providing the optional start parameter as shown in the code below:

for index, item in enumerate(fruits, start=1):
    print(index, item)

The output will be similar to the one above. The only difference will be that the index now starts at 1.

Printing the index value pairs and overriding the default start value

So now you’ve got a handle on the syntax of the enumerate() function in Python. But, as with any tool, it’s important to know when and where to use it.

That’s why we’re going to explore some common use cases for the enumerate() function in the next section!

5 Use Cases of the Python Enumerate Function

The enumerate function in Python is extensively used in scenarios where both the index and the value of an iterable object are of importance to the programmer.

We have listed some of the common use cases for enumerate functions in Python below.

1. How to Use Enumerate with Python Lists

In Python, a list is a built-in data structure that allows you to store multiple items in a single variable. Think of a list as a container where you can put in different items, and they maintain their order.

The enumerate() function can be used on lists in a variety of ways, such as:

A. Accessing List Elements and Their Indices with Python Enumerate

One of the most common use cases for enumerate() is when you need to access both the elements of a list and their indices. Enumerate allows you to do this in a clean and efficient way.

The following is an example of accessing elements of a list and their indices:

fruits = ['apple', 'banana', 'mango', 'grape', 'orange']
for index, fruit in enumerate(fruits):
    print(f"At index {index}, the fruit is {fruit}.")

The output of this code is given in the image below:

Accessing List Elements and Their Indices with Enumerate

B. Modifying List Elements with Python Enumerate

When you need to modify the elements of a list based on their index, enumerate() is an excellent tool. You can access the index within the loop and use it to modify the list.

The following is an example of modifying list elements with the enumerate function:

numbers = [1, 2, 3, 4, 5]

for i, num in enumerate(numbers):
    numbers[i] = num * 2

This Python code creates a list of numbers from 1 to 5. Then, it uses a for loop and the enumerate() function to iterate over the list.

For each iteration, it multiplies the current number (num) by 2 and reassigns it to the same position in the list (numbers[i]).

The result is that every number in the original list is doubled as shown in the image below:

Modifying List Elements with Enumerate

C. Comparing Elements in Two Lists with Python Enumerate

If you’re comparing elements in two different lists, enumerate() can provide the index you need to access elements in both lists at the same time.

The following is an example of using enumerate function to compare elements in two lists:

list1 = [1, 2, 3, 4, 5]
list2 = [1, 2, 3, 0, 5]
for i, value in enumerate(list1):
    if value != list2[i]:
        print(f"Difference at index {i}: {value} (list1) vs {list2[i]} (list2)")

In this code, we first define two lists, list1 and list2. Then, we iterate through list1 using a for loop with enumerate(), which provides the index (i) and the value of each item.

If the current item in list1 doesn’t match the corresponding item in list2, it prints the index of the difference and the differing values from both lists.

The result of this code is shown below:

Comparing Elements in Two Lists with Enumerate

2. How to Use Enumerate with Python Tuples

A tuple in Python is an ordered collection of elements, similar to a list. The only difference is that a tuple is immutable, meaning you can’t change its content after creation.

The following are some of the cases where you can use enumerate with Python tuples.

A. Using Python Enumerate() to Find an Element in a Tuple

When dealing with tuples in Python, you might often need to find if an element exists in a tuple.

The following example code demonstrates using enumerate to find elements in a tuple:

fruits = ('apple', 'banana', 'mango', 'grape', 'orange')
for i, fruit in enumerate(fruits):
    if fruit == 'mango':
        print(f"'mango' found at position {i}")

This code will print “‘mango’ found at position 2” because ‘mango’ is at index 2 in the tuple.

Using enumerate to find an element in a tuple

B. Using Python Enumerate() to Create a Dictionary from a Tuple

If you’ve got a tuple and you need to transform it into a dictionary, Python’s enumerate() function can be your go-to tool.

The example code shows how you can create a dictionary from a tuple using enumerate:

fruits = ('apple', 'banana', 'mango', 'grape', 'orange')

fruit_dict = {i: fruit for i, fruit in enumerate(fruits)}
print(fruit_dict)

This code will print a dictionary where the keys are the indices and the values are the elements from the tuple.

Using enumerate() to create a dictionary from a tuple

3. How to Use Enumerate with Python Dictionaries

In Python, a dictionary is a mutable, unordered collection of key-value pairs, where each key must be unique. Think of it as a real-life dictionary: you look up a word (the key) and get its definition (the value).

Following are some of the cases where you can use enumerate with Python dictionaries:

A. Looping Through Keys and Values of a Dictionary

You can use the enumerate() function to loop through the keys and values of a dictionary.

The enumerate() function adds a counter to an iterable object (like dictionaries), allowing you access to the current index value.

An example of enumerate function with Python dictionary is given below:

example_dict = {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
for i, k in enumerate(example_dict):
    print(i, k)

In this Python code, we first create a dictionary called example_dict. Then, we use the enumerate() function to iterate over the dictionary.

For each iteration, we print the loop count (which is given by i and starts from 0) and the current key (which is k) from the dictionary.

Looping through keys and values of a dictionary

B. Combining Python Enumerate with Items Function

You can also access both keys and values of a dictionary through the items() function together with enumerate(). The items() function returns an iterable collection of key-value pairs as tuples.

The example below demonstrates how you can use the items() function with enumerate():

example_dict = {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
for i, (k, v) in enumerate(example_dict.items()):
    print(i, k, v)

In this code, we create a dictionary named example_dict, then we use the enumerate() function to iterate over the dictionary’s key-value pairs. During each iteration, we print the loop index ‘i’, the current key ‘k’, and its corresponding value ‘v’.

Combining Enumerate with Items Function

You now have a solid understanding of how to use Python’s enumerate() function in some common scenarios. But enumerate() has even more to offer.

Let’s dive into some advanced use cases surrounding enumerate() in the next section!

3 Advanced Use Cases of Python Enumerate

In this section, we will go beyond the basics and explore some of the advanced use cases of the enumerate function in Python.

We will cover the following use cases:

  1. Using Enumerate with Python Classes

  2. Using Enumerate with Enum Classes

  3. Using Enumerate for Order Reversing

Let’s get into it!

1. Using Enumerate with Python Classes

In your Python programming journey, you may come across situations where you want to use enumerate with custom classes.

To achieve this, your class should implement the iter() method, which allows it to be iterable.

Consider a class Color that stores color names and their associated hex values:

class Color:
    def __init__(self, colors: dict):
        self.colors = colors

    def __iter__(self):
        return iter(self.colors.items())

colors = Color({"red": "#FF0000", "green": "#00FF00", "blue": "#0000FF"})

for index, (name, hex_value) in enumerate(colors):
    print(f"{index}: {name} => {hex_value}")

In this code, we are creating a Color class that takes a dictionary of color names and their corresponding hexadecimal values.

When you use enumerate() in the loop, it provides the index along with each key-value pair. This allows you to print the index, the color name, and its hexadecimal value in a formatted string.

Using Enumerate with Python Classes

2. Using Python Enumerate with Enum Classes

Python comes with a built-in Enum class, which allows you to create enumeration types with auto-assigned integer values.

For example, take a look at the following code:

from enum import Enum, auto

class Direction(Enum):
    NORTH = auto()
    EAST = auto()
    SOUTH = auto()
    WEST = auto()

for index, direction in enumerate(Direction):
    print(f"{index}: {direction.name} => {direction.value}")

In this script, we are defining an enumeration Direction with four members (NORTH, EAST, SOUTH, and WEST) using Python’s enum module. The auto() function assigns an automatic value to each member.

When you use enumerate() in the loop, it provides an index along with each enumeration member. This lets you print out the index, the member’s name, and its automatically assigned value in a formatted string.

The output of this code is given in the image below:

Custom Enumeration Classes in Python

3. Using Python Enumerate for Order Reversing

In some cases, you may want to enumerate items in reverse order. You can achieve this by using the reversed() built-in function in combination with enumerate().

The following example demonstrates enumerating items in reversed order:

my_list = ["apple", "banana", "cherry"]

for index, item in enumerate(reversed(my_list)):
    print(f"{index}: {item}")

In this code, we are iterating over a reversed version of my_list using enumerate(). This provides you with the index and the item from the reversed list in each iteration. It allows you to print the index and the item in a formatted string.

Reverse Order Enumeration

The reversed() function will not modify the original sequence; it creates a new iterator that presents the items in reverse order.

To know more about functions in Python, check the following video out:

Final Thoughts

As you continue on your Python journey, mastering the enumerate() function is a must. It’s a tool that enhances code readability and efficiency.

By using enumerate(), you can seamlessly access both the index and the value in your loops, reducing the need for counter-variables or indexing. It simplifies your code and makes it more Pythonic.

Whether you’re iterating through lists, tuples, strings, or dictionaries, enumerate() will prove to be a valuable tool. By understanding and practicing with enumerate(), you’ll be taking a significant step in honing your Python programming skills!

author avatar
Sam McKay, CFA
Sam is Enterprise DNA's CEO & Founder. He helps individuals and organizations develop data driven cultures and create enterprise value by delivering business intelligence training and education.

Related Posts