Sick Gaming
[Tut] Python enumerate() — A Simple Illustrated Guide with Video - Printable Version

+- Sick Gaming (https://www.sickgaming.net)
+-- Forum: Programming (https://www.sickgaming.net/forum-76.html)
+--- Forum: Python (https://www.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

<div><p>If you’re like me, you want to come to the heart of an issue fast. Here’s the <strong>1-paragraph summary</strong> of the <code>enumerate()</code> function—that’s all you need to know to get started using it:</p>
<p class="has-pale-cyan-blue-background-color has-background">Python’s <a href="https://blog.finxter.com/python-built-in-functions/" title="Python Built-In Functions">built-in</a> <code>enumerate(iterable)</code> function allows you to <strong>loop over all elements in an <code>iterable</code> and their associated counters.</strong> Formally, it takes an <code>iterable</code> as an input argument and <strong>returns an iterable of tuples</strong> <code>(i, x)</code>—one per iterable element <code>x</code>. The first integer tuple value is the counter of the element <code>x</code> in the <code>iterable</code>, starting to count from 0. The second tuple value is a reference to the element <code>x</code> itself. For example, <code>enumerate(['a', 'b', 'c'])</code> returns an iterable <code>(0, 'a'), (1, 'b'), (2, 'c')</code>. You can modify the default <strong>start index of the counter</strong> by setting the <strong>optional second integer argument</strong> <code>enumerate(iterable, <strong>start</strong>)</code>. </p>
<p>I’ve created a short visual guide into enumerate in the following graphic:</p>
<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" src="https://blog.finxter.com/wp-content/uploads/2021/01/enumerate-1-1024x576.jpg" alt="Python enumerate()" class="wp-image-20510" width="768" height="432" srcset="https://blog.finxter.com/wp-content/uploads/2021/01/enumerate-1-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uploads/2021/01/enumerate-1-300x169.jpg 300w, https://blog.finxter.com/wp-content/uploads/2021/01/enumerate-1-768x432.jpg 768w, https://blog.finxter.com/wp-content/uploads/2021/01/enumerate-1-150x84.jpg 150w" sizes="(max-width: 768px) 100vw, 768px" /></figure>
</div>
<h2>Usage Example</h2>
<p>Learn by example! Here are some examples of how to use the <code>enumerate()</code> <a href="https://blog.finxter.com/python-built-in-functions/" title="Python Built-In Functions">built-in function</a>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">fruits = ['apple', 'banana', 'cherry']
for counter, value in enumerate(fruits): print(counter, value) # OUTPUT:
# 0 apple
# 1 banana
# 2 cherry
</pre>
<p>The <code>enumerate(iterable, start)</code> function takes an optional second argument that is the start value of the counter.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">fruits = ['apple', 'banana', 'cherry']
for counter, value in enumerate(fruits, 42): print(counter, value) # OUTPUT:
# 42 apple
# 43 banana
# 44 cherry</pre>
<p> 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:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">fruits = ['apple', 'banana', 'cherry']
fruits_with_indices = list(enumerate(fruits))
print(fruits_with_indices)
# [(0, 'apple'), (1, 'banana'), (2, 'cherry')]
</pre>
<h2>Video enumerate()</h2>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe loading="lazy" title="Python enumerate() — A Simple Guide" width="1400" height="788" src="https://www.youtube.com/embed/6SifUNXKWNA?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<h2>Syntax enumerate()</h2>
<pre class="wp-block-preformatted"><strong>Syntax: </strong>
<code><strong>enumerate(iterable)</strong> -> loop over all elements in an iterable and their counters, starting from 0. </code>
<code><strong>enumerate(iterable, start)</strong> -> loop over all elements in an iterable and their counters, starting from <strong>start</strong>. </code></pre>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><strong>Arguments</strong></td>
<td><code>iterable</code></td>
<td>The iterable you want to enumerate.</td>
</tr>
<tr>
<td></td>
<td><code>start</code></td>
<td>The start counter of the first element <code>iterable[0]</code>. </td>
</tr>
<tr>
<td><strong>Return Value</strong></td>
<td><code>enumerate object</code></td>
<td>An iterable that allows you to iterate over each element associated to its counter, starting to count from <code>start</code>. </td>
</tr>
</tbody>
</table>
</figure>
<h2>Interactive Shell Exercise: Understanding enumerate()</h2>
<p>Consider the following interactive code:</p>
<p> <iframe loading="lazy" src="https://trinket.io/embed/python/d9cfb3aaf1" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p>
<p><em><strong>Exercise</strong>: 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?</em></p>
<p>Next, you’re going to dive deeper into the <code>enumerate()</code> function. </p>
<hr class="wp-block-separator"/>
<p><strong>But before we move on, I’m excited to present you my brand-new Python book <a rel="noreferrer noopener" href="https://amzn.to/2WAYeJE" target="_blank" title="https://amzn.to/2WAYeJE">Python One-Liners</a></strong> (Amazon Link).</p>
<p>If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a <strong>single line of Python code.</strong> But it’s also an <strong>introduction to computer science</strong>, data science, machine learning, and algorithms. <strong><em>The universe in a single line of Python!</em></strong></p>
<div class="wp-block-image">
<figure class="aligncenter"><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noopener noreferrer"><img loading="lazy" width="215" height="283" src="https://blog.finxter.com/wp-content/uploads/2020/02/image-1.png" alt="" class="wp-image-5969"/></a></figure>
</div>
<p>The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco). </p>
<p>Link: <a href="https://nostarch.com/pythononeliners" target="_blank" rel="noreferrer noopener">https://nostarch.com/pythononeliners</a></p>
<hr class="wp-block-separator"/>
<h2>What is the Return Value of Python’s enumerate() function?</h2>
<p>The return value of <code>enumerate(iterable)</code> is an object of type enumerate. The enumerate class definition implements the iterable interface—the<a href="https://blog.finxter.com/python-next/" target="_blank" rel="noreferrer noopener" title="Python next()"> <code>__next__()</code></a> function—which means that you can iterate over it. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">fruits = ['apple', 'banana', 'cherry']
print(type(enumerate(fruits)))
# &lt;class 'enumerate'></pre>
<h2>How is Python’s enumerate() Function Implemented?</h2>
<p>The default implementation of <code>enumerate()</code> is done in C++, assuming you use cPython as your Python engine. However, the <a href="https://docs.python.org/3/library/functions.html#enumerate" target="_blank" rel="noreferrer noopener" title="https://docs.python.org/3/library/functions.html#enumerate">documentation </a>shows an equivalent implementation of <code>enumerate()</code> in Python code that helps you understand how it works under the hood:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def enumerate(sequence, start=0): counter = start for element in sequence: yield counter, element counter += 1</pre>
<p>You can see that the return value of <code>enumerate()</code> is not a list but a generator that issues the <code>(counter, element)</code> 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. </p>
<h2>How to Use enumerate() on Strings?</h2>
<p>The <code>enumerate(iterable)</code> function takes an <code>iterable</code> 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)</code> will be an enumerate object that associates a counter to each character in the <code>string</code> for a series of tuples <code>(counter, character)</code>. Here’s an example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> list(enumerate('finxter'))
[(0, 'f'), (1, 'i'), (2, 'n'), (3, 'x'), (4, 't'), (5, 'e'), (6, 'r')]</pre>
<p>You can also set the optional second argument <code>start</code>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> list(enumerate('finxter', 42))
[(42, 'f'), (43, 'i'), (44, 'n'), (45, 'x'), (46, 't'), (47, 'e'), (48, 'r')]</pre>
<h2>How to Make Your Loop More Pythonic With enumerate()?</h2>
<p>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:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># NON_PYTHONIC
fruits = ['apple', 'banana', 'cherry']
for i in range(len(fruits)): print(i, fruits[i])</pre>
<p>The output of this correct, but unpythonic code is:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">0 apple
1 banana
2 cherry</pre>
<p>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()</code> function due its more idiomatic and crisp functionality:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># PYTHONIC
fruits = ['apple', 'banana', 'cherry']
for i, fruit in enumerate(fruits): print(i, fruit)</pre>
<p>You don’t have to use a single <a href="https://blog.finxter.com/daily-python-puzzle-list-indexing/" title="List Indexing" target="_blank" rel="noreferrer noopener">indexing </a>mechanism—which reduces the likelihood of a bug and improves readability of your code. </p>
<h2>Python enumerate() step</h2>
<p>How to set a step in the indices used by the <code>enumerate()</code> function? For example, you may want to use only every third counter:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">0 element_0
3 element_1
6 element_2</pre>
<p>The answer is to multiply the returned counter value from a default call of the enumerate() function with the step size like this:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">lst = ['element_0', 'element_1', 'element_2']
step = 3
for i, x in enumerate(lst): print(i*step, x)
</pre>
<pre class="wp-block-preformatted"><code><strong>OUTPUT:</strong></code>
<code>0 element_0
3 element_1
6 element_2</code></pre>
<h2>Summary</h2>
<p>Python’s <a href="https://blog.finxter.com/python-built-in-functions/">built-in</a> <code>enumerate(iterable)</code> function allows you to <strong>loop over all elements in an <code>iterable</code> and their associated counters.</strong> </p>
<p>Formally, it takes an <code>iterable</code> as an input argument and <strong>returns an iterable of tuples</strong><code>(i, x)</code>—one per iterable element <code>x</code>. </p>
<ul>
<li>The first integer tuple value is the counter of the element <code>x</code> in the <code>iterable</code>, starting to count from 0. </li>
<li>The second tuple value is a reference to the element <code>x</code> itself. </li>
</ul>
<p>For example, <code>enumerate(['a', 'b', 'c'])</code> returns an iterable <code>(0, 'a'), (1, 'b'), (2, 'c')</code>. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print(*enumerate(['a', 'b', 'c']))
# (0, 'a'), (1, 'b'), (2, 'c')</pre>
<p>You can modify the default <strong>start index of the counter</strong> by setting the <strong>optional second integer argument </strong><code>enumerate(iterable, <strong>start</strong>)</code>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print(*enumerate(['a', 'b', 'c'], 10))
# (10, 'a') (11, 'b') (12, 'c')</pre>
<hr class="wp-block-separator"/>
<p>I hope you enjoyed the article! To improve your Python education, you may want to join the popular free <a href="https://blog.finxter.com/email-academy/" target="_blank" rel="noreferrer noopener" title="Email Academy">Finxter Email Academy</a>:</p>
<p>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!</p>
<h2>Where to Go From Here?</h2>
<p>Enough theory, let’s get some practice!</p>
<p>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?</p>
<p><strong>Practice projects is how you sharpen your saw in coding!</strong></p>
<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?</p>
<p>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.</p>
<p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p>
<h2>References:</h2>
<ul>
<li><a href="https://docs.python.org/3/library/functions.html#enumerate" target="_blank" rel="noreferrer noopener">https://docs.python.org/3/library/functions.html#enumerate</a></li>
<li><a href="https://book.pythontips.com/en/latest/enumerate.html" target="_blank" rel="noreferrer noopener">https://book.pythontips.com/en/latest/enumerate.html</a></li>
<li><a href="https://realpython.com/python-enumerate/" target="_blank" rel="noreferrer noopener">https://realpython.com/python-enumerate/</a></li>
<li><a href="https://www.geeksforgeeks.org/enumerate-in-python/" target="_blank" rel="noreferrer noopener">https://www.geeksforgeeks.org/enumerate-in-python/</a></li>
<li><a href="https://www.programiz.com/python-programming/methods/built-in/enumerate" target="_blank" rel="noreferrer noopener">https://www.programiz.com/python-programming/methods/built-in/enumerate</a></li>
<li><a href="https://www.w3schools.com/python/ref_func_enumerate.asp" target="_blank" rel="noreferrer noopener">https://www.w3schools.com/python/ref_func_enumerate.asp</a></li>
<li><a href="https://www.afternerd.com/blog/python-enumerate/" target="_blank" rel="noreferrer noopener">https://www.afternerd.com/blog/python-enumerate/</a></li>
<li><a href="https://careerkarma.com/blog/python-enumerate/" target="_blank" rel="noreferrer noopener">https://careerkarma.com/blog/python-enumerate/</a></li>
</ul>
</p>
<p>The post <a href="https://blog.finxter.com/python-enumerate/">Python enumerate() — A Simple Illustrated Guide with Video</a> first appeared on <a href="https://blog.finxter.com">Finxter</a>. </p>
</div>


https://www.sickgaming.net/blog/2021/01/06/python-enumerate-a-simple-illustrated-guide-with-video/