Skip to content

Python enumerate: Python Looping with Index Counters

Python enumerate Python Looping with Index Counters Cover Image

In this tutorial, you’ll learn how to use the Python enumerate function to improve your Python for loops. The Python enumerate() function allows you to loop over an iterable object, such as lists or dictionaries while accessing the item’s index position. The enumerate() function lets you write significantly cleaner Python for-loops.

By the end of this tutorial, you’ll have learned:

  • What the Python enumerate() function is
  • Why the Python enumerate() function is useful
  • How to use the enumerate() function to loop over Python lists, tuples, strings, and dictionaries
  • How to start at a different index counter using the Python enumerate() function
  • How to use the Python enumerate() function in reverse

Understanding the Python enumerate() Function with a List

The Python enumerate() function is an incredibly versatile function that allows you to access both the index and item of an iterable, while looping over an object. The best way to understand the usefulness of the function is to use it!

Let’s take a look at an example of using the enumerate() function by passing in a list:

# Using the Python enumerate() Function
websites = ['datagy', 'google', 'askjeeves']

for item in enumerate(websites):
    print(item)

# Returns:
# (0, 'datagy')
# (1, 'google')
# (2, 'askjeeves')

We can see that the enumerate() function returns a tuple for each item in the item passed into it. The tuple is made up of the index of the item and the item itself.

Because we can unpack these items right away, we can actually improve how we use this code. Let’s see what this looks like:

# Accessing the Index and Value of Our enumerate Object
websites = ['datagy', 'google', 'askjeeves']

for idx, website in enumerate(websites):
    print(f"{idx} - {website}")

# Returns:
# 0 - datagy
# 1 - google
# 2 - askjeeves

We can see that we were able to unpack both items in the returned tuple. We can then access both the index and the value itself in our iteration.

In the next section, you’ll learn how to better understand the utility of the function by comparing it to other ways of accomplishing the same thing!

Making the Case for the Python enumerate() Function

Without using the Python enumerate() function we’re able to implement something similar by looping over the range of the length of the iterable object.

Let’s see what this looks like:

# How to Access the Index and Item Without enumerate
websites = ['datagy', 'google', 'askjeeves']

for idx in range(len(websites)):
    print(idx, websites[idx])

# 0 datagy
# 1 google
# 2 askjeeves

We can see that this approach works. However, it’s not the most readable approach, and it makes it unclear what we’re actually accessing.

Because it’s important to strive for readability in your code, the Python enumerate() function can make your code much cleaner!

Using Python enumerate With a Different Start Index

So far, we’ve looked at the Python enumerate function by simply passing in a list. The enumerate function, however, also has an optional parameter, start=. As the name implies, this parameter defines the start value for the index.

By default the parameter is set to start=0, meaning that the first index will start at 0. This makes sense, since Python items tend to be 0-indexed. However, in some cases this may not be what you want.

For example, image that you have a list containing directions. In this case, you may want to start at step 1, since step 0 doesn’t make much sense. Let’s see what this looks like:

# Starting at a Different Start Index
directions = ['turn right', 'turn left', 'go straight', 'turn right']

for step, direction in enumerate(directions, start=1):
    print(f'Step {step}: {direction}')

# Returns:
# Step 1: turn right
# Step 2: turn left
# Step 3: go straight
# Step 4: turn right

We can see that this result is much more readable!

Using Python enumerate to Iterate over a Dictionary

Using the Python enumerate() function on a dictionary works a bit differently than you might expect. What happens is that the function returns an “index” starting at 0 (remember, dictionaries aren’t indexed) and the key of the dictionary.

Let’s see what this looks like:

# Using Python enumerate() on a Dictionary
ages = {'Nik':33, 'Kate':32, 'John':31, 'Mike':30}

for idx, item in enumerate(ages):
    print(idx, item)

# Returns:
# 0 Nik
# 1 Kate
# 2 John
# 3 Mike

This may not be what you’re expecting! What you may instead want to do is be able to loop over the key and value of each key:value pair in the dictionary.

In order to do this, you can simply iterate over the return value from the .items() method:

# Iterating over a Key and Value in a Dictionary
ages = {'Nik':33, 'Kate':32, 'John':31, 'Mike':30}

for key, value in ages.items():
    print(key, value)

# Returns:
# Nik 33
# Kate 32
# John 31
# Mike 30

This is much more likely what we were expecting to have returned!

Using Python enumerate In Reverse

In this section, you’ll learn how to use the Python enumerate function to iterate over a list in reverse order. The enumerate function technically returns a generator object. These objects can’t be reversed. Because of this, we first need to turn the result into a list and reverse that object.

Let’s see how this works:

# Using enumerate In Reverse Order
websites = ['datagy', 'google', 'askjeeves']

for idx, website in reversed(list(enumerate(websites))):
    print(idx, website)

# Returns:
# 2 askjeeves
# 1 google
# 0 datagy

At first glance, it may seem intuitive to loop over the list in reverse order. However, this doesn’t return the index in the correct, as it would begin at 0.

Using Python enumerate to Iterate over a Tuple

Using the Python enumerate function to iterate over a tuple works in the same way as using the function on a string. The function will return a tuple containing the index and the item.

Let’s see what this looks like:

# Using enumerate() on a Python tuple
websites = ('datagy', 'google', 'askjeeves')

for idx, website in enumerate(websites):
    print(idx, website)

# Returns:
# 0 datagy
# 1 google
# 2 askjeeves

Using Python enumerate to Iterate over a String

An interesting thing about Python strings is that they are iterable. Because of this, we can also pass a string into the enumerate() function in order to return the index and value pairs. This works in the same way as passing in lists or tuples.

Let’s look over a string passing in a starting at the value of 1:

# Using the Python enumerate() Function on a String
website = 'datagy'

for idx, letter in enumerate(website):
    print(f'Letter {idx} is {letter}')

# Returns:
# Letter 0 is d
# Letter 1 is a
# Letter 2 is t
# Letter 3 is a
# Letter 4 is g
# Letter 5 is y

Conclusion

In this tutorial, you learned how to use the Python enumerate() function to loop over an object while accessing both the index and the value at the same time. You explored how the function works and why it’s better than other approaches.

Then, you learned how to use the Python enumerate() function with a different start index and in reverse order. Then, you learned how to use the function to iterate over a dictionary, a tuple, and a string.

Additional Resources

To learn more about related topics, check out the tutorials below:

Tags:

Leave a Reply

Your email address will not be published.