{"id":122868,"date":"2021-01-06T14:19:34","date_gmt":"2021-01-06T14:19:34","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=20466"},"modified":"2021-01-06T14:19:34","modified_gmt":"2021-01-06T14:19:34","slug":"python-enumerate-a-simple-illustrated-guide-with-video","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2021\/01\/06\/python-enumerate-a-simple-illustrated-guide-with-video\/","title":{"rendered":"Python enumerate() \u2014 A Simple Illustrated Guide with Video"},"content":{"rendered":"<p>If you&#8217;re like me, you want to come to the heart of an issue fast. Here&#8217;s the <strong>1-paragraph summary<\/strong> of the <code>enumerate()<\/code> function&#8212;that&#8217;s all you need to know to get started using it:<\/p>\n<p class=\"has-pale-cyan-blue-background-color has-background\">Python&#8217;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>&#8212;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>\n<p>I&#8217;ve created a short visual guide into enumerate in the following graphic:<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large is-resized\"><img decoding=\"async\" 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=\"auto, (max-width: 768px) 100vw, 768px\" \/><\/figure>\n<\/div>\n<h2>Usage Example<\/h2>\n<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>\n<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']\nfor counter, value in enumerate(fruits): print(counter, value) # OUTPUT:\n# 0 apple\n# 1 banana\n# 2 cherry\n<\/pre>\n<p>The <code>enumerate(iterable, start)<\/code> function takes an optional second argument that is the start value of the counter.<\/p>\n<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']\nfor counter, value in enumerate(fruits, 42): print(counter, value) # OUTPUT:\n# 42 apple\n# 43 banana\n# 44 cherry<\/pre>\n<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>\n<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']\nfruits_with_indices = list(enumerate(fruits))\nprint(fruits_with_indices)\n# [(0, 'apple'), (1, 'banana'), (2, 'cherry')]\n<\/pre>\n<h2>Video enumerate()<\/h2>\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<div class=\"ast-oembed-container\"><iframe loading=\"lazy\" title=\"Python enumerate() \u2014 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>\n<\/div>\n<\/figure>\n<h2>Syntax enumerate()<\/h2>\n<pre class=\"wp-block-preformatted\"><strong>Syntax: <\/strong>\n<code><strong>enumerate(iterable)<\/strong> -> loop over all elements in an iterable and their counters, starting from 0. <\/code>\n<code><strong>enumerate(iterable, start)<\/strong> -> loop over all elements in an iterable and their counters, starting from <strong>start<\/strong>. <\/code><\/pre>\n<figure class=\"wp-block-table is-style-stripes\">\n<table>\n<tbody>\n<tr>\n<td><strong>Arguments<\/strong><\/td>\n<td><code>iterable<\/code><\/td>\n<td>The iterable you want to enumerate.<\/td>\n<\/tr>\n<tr>\n<td><\/td>\n<td><code>start<\/code><\/td>\n<td>The start counter of the first element <code>iterable[0]<\/code>. <\/td>\n<\/tr>\n<tr>\n<td><strong>Return Value<\/strong><\/td>\n<td><code>enumerate object<\/code><\/td>\n<td>An iterable that allows you to iterate over each element associated to its counter, starting to count from <code>start<\/code>. <\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n<h2>Interactive Shell Exercise: Understanding enumerate()<\/h2>\n<p>Consider the following interactive code:<\/p>\n<p> <iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/embed\/python\/d9cfb3aaf1\" width=\"100%\" height=\"356\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" allowfullscreen><\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: Change the start value of the enumerate function to your personal age and run the code. What&#8217;s the associated counter to the last fruit in the list?<\/em><\/p>\n<p>Next, you&#8217;re going to dive deeper into the <code>enumerate()<\/code> function. <\/p>\n<hr class=\"wp-block-separator\"\/>\n<p><strong>But before we move on, I&#8217;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>\n<p>If you like one-liners, you&#8217;ll LOVE the book. It&#8217;ll teach you everything there is to know about a <strong>single line of Python code.<\/strong> But it&#8217;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>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><a href=\"https:\/\/amzn.to\/2WAYeJE\" target=\"_blank\" rel=\"noopener noreferrer\"><img decoding=\"async\" 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>\n<\/div>\n<p>The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco). <\/p>\n<p>Link: <a href=\"https:\/\/nostarch.com\/pythononeliners\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/nostarch.com\/pythononeliners<\/a><\/p>\n<hr class=\"wp-block-separator\"\/>\n<h2>What is the Return Value of Python&#8217;s enumerate() function?<\/h2>\n<p>The return value of <code>enumerate(iterable)<\/code> is an object of type enumerate. The enumerate class definition implements the iterable interface&#8212;the<a href=\"https:\/\/blog.finxter.com\/python-next\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python next()\"> <code>__next__()<\/code><\/a> function&#8212;which means that you can iterate over it. <\/p>\n<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']\nprint(type(enumerate(fruits)))\n# &lt;class 'enumerate'><\/pre>\n<h2>How is Python&#8217;s enumerate() Function Implemented?<\/h2>\n<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>\n<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>\n<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&#8212;it doesn&#8217;t generate all (counter, element) pairs in advance and holds them in memory, but generates them as they&#8217;re needed. <\/p>\n<h2>How to Use enumerate() on Strings?<\/h2>\n<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&#8217;s an example:<\/p>\n<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'))\n[(0, 'f'), (1, 'i'), (2, 'n'), (3, 'x'), (4, 't'), (5, 'e'), (6, 'r')]<\/pre>\n<p>You can also set the optional second argument <code>start<\/code>:<\/p>\n<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))\n[(42, 'f'), (43, 'i'), (44, 'n'), (45, 'x'), (46, 't'), (47, 'e'), (48, 'r')]<\/pre>\n<h2>How to Make Your Loop More Pythonic With enumerate()?<\/h2>\n<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>\n<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\nfruits = ['apple', 'banana', 'cherry']\nfor i in range(len(fruits)): print(i, fruits[i])<\/pre>\n<p>The output of this correct, but unpythonic code is:<\/p>\n<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\n1 banana\n2 cherry<\/pre>\n<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>\n<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\nfruits = ['apple', 'banana', 'cherry']\nfor i, fruit in enumerate(fruits): print(i, fruit)<\/pre>\n<p>You don&#8217;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&#8212;which reduces the likelihood of a bug and improves readability of your code. <\/p>\n<h2>Python enumerate() step<\/h2>\n<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>\n<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\n3 element_1\n6 element_2<\/pre>\n<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>\n<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']\nstep = 3\nfor i, x in enumerate(lst): print(i*step, x)\n<\/pre>\n<pre class=\"wp-block-preformatted\"><code><strong>OUTPUT:<\/strong><\/code>\n<code>0 element_0\n3 element_1\n6 element_2<\/code><\/pre>\n<h2>Summary<\/h2>\n<p>Python&#8217;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>\n<p>Formally, it takes an <code>iterable<\/code> as an input argument and <strong>returns an iterable of tuples<\/strong><code>(i, x)<\/code>&#8212;one per iterable element <code>x<\/code>. <\/p>\n<ul>\n<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>\n<li>The second tuple value is a reference to the element <code>x<\/code> itself. <\/li>\n<\/ul>\n<p>For example, <code>enumerate(['a', 'b', 'c'])<\/code> returns an iterable <code>(0, 'a'), (1, 'b'), (2, 'c')<\/code>. <\/p>\n<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']))\n# (0, 'a'), (1, 'b'), (2, 'c')<\/pre>\n<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>\n<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))\n# (10, 'a') (11, 'b') (12, 'c')<\/pre>\n<hr class=\"wp-block-separator\"\/>\n<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>\n<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>\n<h2>Where to Go From Here?<\/h2>\n<p>Enough theory, let\u2019s get some practice!<\/p>\n<p>To become successful in coding, you need to get out there and solve real problems for real people. That\u2019s how you can become a six-figure earner easily. And that\u2019s how you polish the skills you really need in practice. After all, what\u2019s the use of learning theory that nobody ever needs?<\/p>\n<p><strong>Practice projects is how you sharpen your saw in coding!<\/strong><\/p>\n<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>\n<p>Then become a Python freelance developer! It\u2019s the best way of approaching the task of improving your Python skills\u2014even if you are a complete beginner.<\/p>\n<p>Join my free webinar <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\">\u201cHow to Build Your High-Income Skill Python\u201d<\/a> and watch how I grew my coding business online and how you can, too\u2014from the comfort of your own home.<\/p>\n<p><a href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\" rel=\"noreferrer noopener\">Join the free webinar now!<\/a><\/p>\n<h2>References:<\/h2>\n<ul>\n<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>\n<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>\n<li><a href=\"https:\/\/realpython.com\/python-enumerate\/\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/realpython.com\/python-enumerate\/<\/a><\/li>\n<li><a href=\"https:\/\/www.geeksforgeeks.org\/enumerate-in-python\/\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/www.geeksforgeeks.org\/enumerate-in-python\/<\/a><\/li>\n<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>\n<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>\n<li><a href=\"https:\/\/www.afternerd.com\/blog\/python-enumerate\/\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/www.afternerd.com\/blog\/python-enumerate\/<\/a><\/li>\n<li><a href=\"https:\/\/careerkarma.com\/blog\/python-enumerate\/\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/careerkarma.com\/blog\/python-enumerate\/<\/a><\/li>\n<\/ul>\n<\/p>\n<p>The post <a href=\"https:\/\/blog.finxter.com\/python-enumerate\/\">Python enumerate() \u2014 A Simple Illustrated Guide with Video<\/a> first appeared on <a href=\"https:\/\/blog.finxter.com\">Finxter<\/a>. <\/p>\n","protected":false},"excerpt":{"rendered":"<p>If you&#8217;re like me, you want to come to the heart of an issue fast. Here&#8217;s the 1-paragraph summary of the enumerate() function&#8212;that&#8217;s all you need to know to get started using it: Python&#8217;s built-in enumerate(iterable) function allows you to loop over all elements in an iterable and their associated counters. Formally, it takes an [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-122868","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/122868","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=122868"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/122868\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=122868"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=122868"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=122868"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}