![]() |
|
[Tut] Python enumerate() — A Simple Illustrated Guide with Video - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Python enumerate() — A Simple Illustrated Guide with Video (/thread-99062.html) |
[Tut] Python enumerate() — A Simple Illustrated Guide with Video - xSicKxBot - 03-25-2022 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()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: ![]() 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! ![]() 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
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:
The post Python enumerate() — A Simple Illustrated Guide with Video first appeared on Finxter. |