03-25-2022, 09:14 AM
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 function—that’s all you need to know to get started using it:
Python’s built-in function allows you to loop over all elements in an and their associated counters. Formally, it takes an as an input argument and returns an iterable of tuples —one per iterable element . The first integer tuple value is the counter of the element in the , starting to count from 0. The second tuple value is a reference to the element itself. For example, returns an iterable . You can modify the default start index of the counter by setting the optional second integer argument .
I’ve created a short visual guide into enumerate in the following graphic:
![[Image: enumerate-1-1024x576.jpg]](https://blog.finxter.com/wp-content/uploads/2021/01/enumerate-1-1024x576.jpg)
Usage Example
Learn by example! Here are some examples of how to use the built-in function:
The function takes an optional second argument that is the start value of the counter.
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:
Video enumerate()
Syntax enumerate()
Arguments |
|
The iterable you want to enumerate.
|
|
The start counter of the first element.
Return Value |
|
An iterable that allows you to iterate over each element associated to its counter, starting to count from.
Interactive Shell Exercise: Understanding enumerate()
Consider the following interactive code:
https://trinket.io/embed/python/d9cfb3aaf1
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 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!
![[Image: image-1.png]](https://blog.finxter.com/wp-content/uploads/2020/02/image-1.png)
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 is an object of type enumerate. The enumerate class definition implements the iterable interface—the function—which means that you can iterate over it.
How is Python’s enumerate() Function Implemented?
The default implementation of is done in C++, assuming you use cPython as your Python engine. However, the documentationshows an equivalent implementation of in Python code that helps you understand how it works under the hood:
You can see that the return value of is not a list but a generator that issues the 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 function takes an as an input argument. A string is an iterable, so you can pass the string as an input. The return value of the function will be an enumerate object that associates a counter to each character in the for a series of tuples . Here’s an example:
You can also set the optional second argument:
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:
The output of this correct, but unpythonic code is:
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 function due its more idiomatic and crisp functionality:
You don’t have to use a single indexingmechanism—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 function? For example, you may want to use only every third counter:
The answer is to multiply the returned counter value from a default call of the enumerate() function with the step size like this:
Summary
Python’s built-in function allows you to loop over all elements in an and their associated counters.
Formally, it takes an as an input argument and returns an iterable of tuples—one per iterable element .
For example, returns an iterable .
You can modify the default start index of the counter by setting the optional second integer argument.
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:
The post Python enumerate() — A Simple Illustrated Guide with Video first appeared on Finxter.
If you’re like me, you want to come to the heart of an issue fast. Here’s the 1-paragraph summary of the
Code:
enumerate()Python’s built-in
Code:
enumerate(iterable)Code:
iterableCode:
iterableCode:
(i, x)Code:
xCode:
xCode:
iterableCode:
xCode:
enumerate(['a', 'b', 'c'])Code:
(0, 'a'), (1, 'b'), (2, 'c')Code:
enumerate(iterable, start)I’ve created a short visual guide into enumerate in the following graphic:
![[Image: enumerate-1-1024x576.jpg]](https://blog.finxter.com/wp-content/uploads/2021/01/enumerate-1-1024x576.jpg)
Usage Example
Learn by example! Here are some examples of how to use the
Code:
enumerate()Code:
fruits = ['apple', 'banana', 'cherry']
for counter, value in enumerate(fruits): print(counter, value) # OUTPUT:
# 0 apple
# 1 banana
# 2 cherryThe
Code:
enumerate(iterable, start)Code:
fruits = ['apple', 'banana', 'cherry']
for counter, value in enumerate(fruits, 42): print(counter, value) # OUTPUT:
# 42 apple
# 43 banana
# 44 cherryYou 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:
Code:
fruits = ['apple', 'banana', 'cherry']
fruits_with_indices = list(enumerate(fruits))
print(fruits_with_indices)
# [(0, 'apple'), (1, 'banana'), (2, 'cherry')]Syntax enumerate()
Code:
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.Arguments |
Code:
iterableThe iterable you want to enumerate.
|
Code:
startThe start counter of the first element
Code:
iterable[0]Return Value |
Code:
enumerate objectAn iterable that allows you to iterate over each element associated to its counter, starting to count from
Code:
startInteractive Shell Exercise: Understanding enumerate()
Consider the following interactive code:
https://trinket.io/embed/python/d9cfb3aaf1
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
Code:
enumerate()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!
![[Image: image-1.png]](https://blog.finxter.com/wp-content/uploads/2020/02/image-1.png)
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
Code:
enumerate(iterable)Code:
__next__()Code:
fruits = ['apple', 'banana', 'cherry']
print(type(enumerate(fruits)))
# <class 'enumerate'>The default implementation of
Code:
enumerate()Code:
enumerate()Code:
def enumerate(sequence, start=0): counter = start for element in sequence: yield counter, element counter += 1You can see that the return value of
Code:
enumerate()Code:
(counter, element)How to Use enumerate() on Strings?
The
Code:
enumerate(iterable)Code:
iterableCode:
enumerate(string)Code:
stringCode:
(counter, character)Code:
>>> 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
Code:
startCode:
>>> list(enumerate('finxter', 42))
[(42, 'f'), (43, 'i'), (44, 'n'), (45, 'x'), (46, 't'), (47, 'e'), (48, 'r')]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:
Code:
# 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:
Code:
0 apple
1 banana
2 cherryWhile 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
Code:
enumerate()Code:
# PYTHONIC
fruits = ['apple', 'banana', 'cherry']
for i, fruit in enumerate(fruits): print(i, fruit)You don’t have to use a single indexingmechanism—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
Code:
enumerate()Code:
0 element_0
3 element_1
6 element_2The answer is to multiply the returned counter value from a default call of the enumerate() function with the step size like this:
Code:
lst = ['element_0', 'element_1', 'element_2']
step = 3
for i, x in enumerate(lst): print(i*step, x)Code:
OUTPUT:
0 element_0
3 element_1
6 element_2Python’s built-in
Code:
enumerate(iterable)Code:
iterableFormally, it takes an
Code:
iterableCode:
(i, x)Code:
x- The first integer tuple value is the counter of the element in theCode:
x, starting to count from 0.Code:iterable
- The second tuple value is a reference to the element itself.Code:
x
For example,
Code:
enumerate(['a', 'b', 'c'])Code:
(0, 'a'), (1, 'b'), (2, 'c')Code:
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
Code:
enumerate(iterable, start)Code:
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:
- https://docs.python.org/3/library/functi...#enumerate
- https://book.pythontips.com/en/latest/enumerate.html
- https://realpython.com/python-enumerate/
- https://www.geeksforgeeks.org/enumerate-in-python/
- https://www.programiz.com/python-program.../enumerate
- https://www.w3schools.com/python/ref_func_enumerate.asp
- https://www.afternerd.com/blog/python-enumerate/
- https://careerkarma.com/blog/python-enumerate/
The post Python enumerate() — A Simple Illustrated Guide with Video first appeared on Finxter.

