Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python enumerate() — A Simple Illustrated Guide with Video
1
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
Code:
enumerate()
function—that’s all you need to know to get started using it:

Python’s built-in
Code:
enumerate(iterable)
function allows you to loop over all elements in an
Code:
iterable
and their associated counters.
Formally, it takes an
Code:
iterable
as an input argument and returns an iterable of tuples
Code:
(i, x)
—one per iterable element
Code:
x
. The first integer tuple value is the counter of the element
Code:
x
in the
Code:
iterable
, starting to count from 0. The second tuple value is a reference to the element
Code:
x
itself. For example,
Code:
enumerate(['a', 'b', 'c'])
returns an iterable
Code:
(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)
.

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

[Image: enumerate-1-1024x576.jpg]

Usage Example

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

Code:
fruits = ['apple', 'banana', 'cherry'] for counter, value in enumerate(fruits): print(counter, value) # OUTPUT: # 0 apple # 1 banana # 2 cherry

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

Code:
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:

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



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:
iterable
|
The iterable you want to enumerate.

|
Code:
start
|
The start counter of the first element
Code:
iterable[0]
.

Return Value |
Code:
enumerate object
|
An iterable that allows you to iterate over each element associated to its counter, starting to count from
Code:
start
.

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
Code:
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!

[Image: 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)
is an object of type enumerate. The enumerate class definition implements the iterable interface—the
Code:
__next__()
function—which means that you can iterate over it.

Code:
fruits = ['apple', 'banana', 'cherry'] print(type(enumerate(fruits))) # <class 'enumerate'>
How is Python’s enumerate() Function Implemented?

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

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

You can see that the return value of
Code:
enumerate()
is not a list but a generator that issues the
Code:
(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
Code:
enumerate(iterable)
function takes an
Code:
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
Code:
enumerate(string)
will be an enumerate object that associates a counter to each character in the
Code:
string
for a series of tuples
Code:
(counter, character)
. Here’s an example:

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:
start
:

Code:
>>> 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:

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 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
Code:
enumerate()
function due its more idiomatic and crisp functionality:

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()
function? For example, you may want to use only every third counter:

Code:
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:

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_2
Summary

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


Formally, it takes an
Code:
iterable
as an input argument and returns an iterable of tuples
Code:
(i, x)
—one per iterable element
Code:
x
.
  • The first integer tuple value is the counter of the element
    Code:
    x
    in the
    Code:
    iterable
    , starting to count from 0.

  • The second tuple value is a reference to the element
    Code:
    x
    itself.

For example,
Code:
enumerate(['a', 'b', 'c'])
returns an iterable
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:

The post Python enumerate() — A Simple Illustrated Guide with Video first appeared on Finxter.
Reply

Users browsing this thread:
1 Guest(s)


Forum Jump: