Python enumerate() — A Simple Illustrated Guide with Video

If you’re like me, you want to come to the heart of an issue fast. Here’s the 1-paragraph summary of the enumerate() function—that’s all you need to know to get started using it:

Python’s built-in enumerate(iterable) function allows you to loop over all elements in an iterable and their associated counters. Formally, it takes an iterable as an input argument and returns an iterable of tuples (i, x)—one per iterable element x. The first integer tuple value is the counter of the element x in the iterable, starting to count from 0. The second tuple value is a reference to the element x itself. For example, enumerate(['a', 'b', 'c']) returns an iterable (0, 'a'), (1, 'b'), (2, 'c'). You can modify the default start index of the counter by setting the optional second integer argument enumerate(iterable, start).

I’ve created a short visual guide into enumerate in the following graphic:

Python enumerate()

Usage Example

Learn by example! Here are some examples of how to use the enumerate() built-in function:

fruits = ['apple', 'banana', 'cherry']
for counter, value in enumerate(fruits):
    print(counter, value)

# OUTPUT:
# 0 apple
# 1 banana
# 2 cherry

The enumerate(iterable, start) function takes an optional second argument that is the start value of the counter.

fruits = ['apple', 'banana', 'cherry']
for counter, value in enumerate(fruits, 42):
    print(counter, value)

# OUTPUT:
# 42 apple
# 43 banana
# 44 cherry

You can use the enumerate function to create a list of tuples from an iterable where the first tuple value is the index of the element:

fruits = ['apple', 'banana', 'cherry']
fruits_with_indices = list(enumerate(fruits))
print(fruits_with_indices)
# [(0, 'apple'), (1, 'banana'), (2, 'cherry')]

Video enumerate()

Syntax enumerate()

Syntax: 
enumerate(iterable) -> loop over all elements in an iterable and their counters, starting from 0. 
enumerate(iterable, start) -> loop over all elements in an iterable and their counters, starting from start. 
ArgumentsiterableThe iterable you want to enumerate.
startThe start counter of the first element iterable[0].
Return Valueenumerate objectAn iterable that allows you to iterate over each element associated to its counter, starting to count from start.

Interactive Shell Exercise: Understanding enumerate()

Consider the following interactive code:

Exercise: Change the start value of the enumerate function to your personal age and run the code. What’s the associated counter to the last fruit in the list?

Next, you’re going to dive deeper into the enumerate() function.


But before we move on, I’m excited to present you my brand-new Python book Python One-Liners (Amazon Link).

If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!

The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).

Link: https://nostarch.com/pythononeliners


What is the Return Value of Python’s enumerate() function?

The return value of enumerate(iterable) is an object of type enumerate. The enumerate class definition implements the iterable interface—the __next__() function—which means that you can iterate over it.

fruits = ['apple', 'banana', 'cherry']
print(type(enumerate(fruits)))
# <class 'enumerate'>

How is Python’s enumerate() Function Implemented?

The default implementation of enumerate() is done in C++, assuming you use cPython as your Python engine. However, the documentation shows an equivalent implementation of enumerate() in Python code that helps you understand how it works under the hood:

def enumerate(sequence, start=0):
    counter = start
    for element in sequence:
        yield counter, element
        counter += 1

You can see that the return value of enumerate() is not a list but a generator that issues the (counter, element) tuples as they appear in the sequence. Thus, the implementation is memory efficient—it doesn’t generate all (counter, element) pairs in advance and holds them in memory, but generates them as they’re needed.

How to Use enumerate() on Strings?

The enumerate(iterable) function takes an iterable as an input argument. A string is an iterable, so you can pass the string as an input. The return value of the function enumerate(string) will be an enumerate object that associates a counter to each character in the string for a series of tuples (counter, character). Here’s an example:

>>> list(enumerate('finxter'))
[(0, 'f'), (1, 'i'), (2, 'n'), (3, 'x'), (4, 't'), (5, 'e'), (6, 'r')]

You can also set the optional second argument start:

>>> list(enumerate('finxter', 42))
[(42, 'f'), (43, 'i'), (44, 'n'), (45, 'x'), (46, 't'), (47, 'e'), (48, 'r')]

How to Make Your Loop More Pythonic With enumerate()?

Beginner Python coders and coders coming from other programming languages such as Java or C++, often think in indices when creating loops such as this one:

# NON_PYTHONIC
fruits = ['apple', 'banana', 'cherry']
for i in range(len(fruits)):
    print(i, fruits[i])

The output of this correct, but unpythonic code is:

0 apple
1 banana
2 cherry

While the code does what it needs to do, it shouts into the world that its creator is not an experienced Python coder, but a newbie in Python. Why? Because an experienced Python coder will always prefer the enumerate() function due its more idiomatic and crisp functionality:

# PYTHONIC
fruits = ['apple', 'banana', 'cherry']
for i, fruit in enumerate(fruits):
    print(i, fruit)

You don’t have to use a single indexing mechanism—which reduces the likelihood of a bug and improves readability of your code.

Python enumerate() step

How to set a step in the indices used by the enumerate() function? For example, you may want to use only every third counter:

0 element_0
3 element_1
6 element_2

The answer is to multiply the returned counter value from a default call of the enumerate() function with the step size like this:

lst = ['element_0', 'element_1', 'element_2']
step = 3
for i, x in enumerate(lst):
    print(i*step, x)
OUTPUT:
0 element_0
3 element_1
6 element_2

Summary

Python’s built-in enumerate(iterable) function allows you to loop over all elements in an iterable and their associated counters.

Formally, it takes an iterable as an input argument and returns an iterable of tuples(i, x)—one per iterable element x.

  • The first integer tuple value is the counter of the element x in the iterable, starting to count from 0.
  • The second tuple value is a reference to the element x itself.

For example, enumerate(['a', 'b', 'c']) returns an iterable (0, 'a'), (1, 'b'), (2, 'c').

print(*enumerate(['a', 'b', 'c']))
# (0, 'a'), (1, 'b'), (2, 'c')

You can modify the default start index of the counter by setting the optional second integer argument enumerate(iterable, start).

print(*enumerate(['a', 'b', 'c'], 10))
# (10, 'a') (11, 'b') (12, 'c')

I hope you enjoyed the article! To improve your Python education, you may want to join the popular free Finxter Email Academy:

Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder!

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

References: