{"id":806,"date":"2018-06-25T04:03:39","date_gmt":"2018-06-25T04:03:39","guid":{"rendered":"http:\/\/www.afternerd.com\/blog\/?p=806"},"modified":"2019-08-20T21:58:28","modified_gmt":"2019-08-20T21:58:28","slug":"python-enumerate","status":"publish","type":"post","link":"https:\/\/www.afternerd.com\/blog\/python-enumerate\/","title":{"rendered":"Python Enumerate Explained (With Examples)"},"content":{"rendered":"<p>How do I get the index of an element while I am iterating over a list?<\/p>\n<p>If you are coming from other programming languages (like C), most likely you are used to the idea of iterating over the length of an array by an index and then using this index to get the value at that location.\u00a0\ud83d\ude13\ud83d\ude13\ud83d\ude13<\/p>\n<p>Python gives you the luxury of iterating directly over the values of the list which is most of the time what you need.<\/p>\n<p>However, there are times when you actually need the index of the item as well.<\/p>\n<p>Python has a built-in function called <span class=\"symbol\">enumerate<\/span> that allows you to do just that.<\/p>\n<p>In this article, I will show you how to iterate over different types of python objects and get back both the index and the value of each item.<\/p>\n<p>Jump directly to a specific section:<\/p>\n<ul>\n<li><a href=\"#enumerate-list\">Enumerate a List<\/a><\/li>\n<li><a href=\"#enumerate-tuple\">Enumerate a Tuple<\/a><\/li>\n<li><a href=\"#enumerate-list-tuples\">Enumerate a List of Tuples (The Neat Way)<\/a><\/li>\n<li><a href=\"#enumerate-string\">Enumerate a String<\/a><\/li>\n<li><a href=\"#enumerate-different-start\">Enumerate with a Different Starting Index<\/a><\/li>\n<li><a href=\"#enumerate-dictionaries-sets\">Why It doesn\u2019t Make Sense to Enumerate Dictionaries and Sets<\/a><\/li>\n<li><a href=\"#deep-dive\">Advanced: Enumerate Deep Dive<\/a><\/li>\n<\/ul>\n<h2 id=\"enumerate-list\">Enumerate a List<\/h2>\n<p>Let&#8217;s see what to do if we want to enumerate a python list.<\/p>\n<p>You can iterate over the index and value of an item in a list by using a basic for loop<\/p>\n<pre class=\"prettyprint\"><code>L = ['apples', 'bananas', 'oranges']\r\nfor idx, val in enumerate(L):\r\n  print(\"index is %d and value is %s\" % (idx, val))<\/code><\/pre>\n<p>The code above will have this output:<\/p>\n<pre class=\"prettyprint\"><code>index is 0 and value is apples\r\nindex is 1 and value is bananas\r\nindex is 2 and value is oranges<\/code><\/pre>\n<p>How easy was that!<\/p>\n<p>Now let&#8217;s see how to enumerate a tuple.<\/p>\n<h2 id=\"enumerate-tuple\">Enumerate a Tuple<\/h2>\n<p>Enumerating a tuple isn&#8217;t at all different from enumerating a list.<\/p>\n<pre class=\"prettyprint\"><code>t = ('apples', 'bananas', 'oranges')\r\nfor idx, val in enumerate(t):\r\n  print(\"index is %d and value is %s\" % (idx, val))<\/code><\/pre>\n<p>And as you expect, the output will be:<\/p>\n<pre class=\"prettyprint\"><code>index is 0 and value is apples\r\nindex is 1 and value is bananas\r\nindex is 2 and value is oranges<\/code><\/pre>\n<p>Now that you know how to enumerate a list and a tuple, how can you enumerate a list of tuples?\u00a0\ud83e\udd14\ud83e\udd14\ud83e\udd14<\/p>\n<h2 id=\"enumerate-list-tuples\">Enumerate a List of Tuples (The Neat Way)<\/h2>\n<p>Say you have a list of tuples where each tuple is a <strong>name-age<\/strong> pair.<\/p>\n<pre class=\"prettyprint\"><code>L = [('Matt', 20), ('Karim', 30), ('Maya', 40)]<\/code><\/pre>\n<p>Of course one way to enumerate the list is like this:<\/p>\n<pre class=\"prettyprint\"><code>for idx, val in enumerate(L):\r\n  name = val[0]\r\n  age = val[1]\r\n  print(\"index is %d, name is %s, and age is %d\" \\\r\n         % (idx, name, age))<\/code><\/pre>\n<p>The above code will definitely work and it will print out this output.<\/p>\n<pre class=\"prettyprint\"><code>index is 0, name is Matt, and age is 20\r\nindex is 1, name is Karim, and age is 30\r\nindex is 2, name is Maya, and age is 40<\/code><\/pre>\n<p>However, a cleaner way to achieve this is through\u00a0<strong>tuple unpacking<\/strong><\/p>\n<p>With tuple unpacking, we can do something like this<\/p>\n<pre class=\"prettyprint\"><code>for idx, (name, age) in enumerate(L):\r\n  print(\"index is %d, name is %s, and age is %d\" \\\r\n        % (idx, name, age))<\/code><\/pre>\n<h2 id=\"enumerate-string\">Enumerate a String<\/h2>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-824\" src=\"http:\/\/www.afternerd.com\/blog\/wp-content\/uploads\/2018\/06\/alphabet.png\" alt=\"enumerate-string\" width=\"560\" height=\"315\" srcset=\"https:\/\/www.afternerd.com\/blog\/wp-content\/uploads\/2018\/06\/alphabet.png 560w, https:\/\/www.afternerd.com\/blog\/wp-content\/uploads\/2018\/06\/alphabet-300x169.png 300w, https:\/\/www.afternerd.com\/blog\/wp-content\/uploads\/2018\/06\/alphabet-200x113.png 200w, https:\/\/www.afternerd.com\/blog\/wp-content\/uploads\/2018\/06\/alphabet-400x225.png 400w\" sizes=\"(max-width: 560px) 100vw, 560px\" \/><\/p>\n<p>So what happens when you use the enumerate function on a string object?<\/p>\n<p>An item in a string is a single character.<\/p>\n<p>So if you enumerate over a string, you will get back the index and value of each character in the string.<\/p>\n<p>Let&#8217;s take an example:<\/p>\n<pre class=\"prettyprint\"><code>str = \"Python\"\r\nfor idx, ch in enumerate(str):\r\n  print(\"index is %d and character is %s\" \\\r\n         % (idx, ch))<\/code><\/pre>\n<p>And the output will be:<\/p>\n<pre class=\"prettyprint\"><code>index is 0 and character is P\r\nindex is 1 and character is y\r\nindex is 2 and character is t\r\nindex is 3 and character is h\r\nindex is 4 and character is o\r\nindex is 5 and character is n<\/code><\/pre>\n<h2 id=\"enumerate-different-start\">Enumerate with a Different Starting Index<\/h2>\n<p>So as you know, indices in python start at 0.<\/p>\n<p>This means that when you use the <strong>enumerate<\/strong> function, the index returned for the first item will be 0.<\/p>\n<p>However, in some cases, you want the loop counter to start at a different number.<\/p>\n<p><strong>enumerate<\/strong> allows you to do that through an optional start parameter.<\/p>\n<p>For example, let&#8217;s say we want to enumerate over a list starting at 1.<\/p>\n<p>The code will look like this:<\/p>\n<pre class=\"prettyprint\"><code>L = ['apples', 'bananas', 'oranges']\r\nfor idx, s in enumerate(L, start = 1):\r\n  print(\"index is %d and value is %s\" \\\r\n         % (idx, s))<\/code><\/pre>\n<p>The above code will result in this output.<\/p>\n<pre class=\"prettyprint\"><code>index is 1 and value is apples\r\nindex is 2 and value is bananas\r\nindex is 3 and value is oranges<\/code><\/pre>\n<p>Needless to say, you can also start with a negative number.<\/p>\n<h2 id=\"enumerate-dictionaries-sets\">Why It doesn&#8217;t Make Sense to Enumerate Dictionaries and Sets<\/h2>\n<p>So does it make sense to use the <span class=\"symbol\">enumerate<\/span> function for dictionaries and sets?<\/p>\n<p><strong>Absolutely not!<\/strong><\/p>\n<p>Think about it, the only reason you would use <span class=\"symbol\">enumerate<\/span> is when you actually care about the index of the item.<\/p>\n<p>Dictionaries and Sets are not sequences.<\/p>\n<p>Their items do not have an index, and they don&#8217;t, by definition, need one.<\/p>\n<p>If you want to iterate over the keys and values of a dictionary instead (a very common operation), then you can do that using the following code:<\/p>\n<pre class=\"prettyprint\"><code>d = {'a': 1, 'b': 2, 'c': 3}\r\nfor k, v in d.items():\r\n  # k is now the key\r\n  # v is the value\r\n  print(k, v)<\/code><\/pre>\n<p>And if you want to iterate over a set, then just use a regular for loop.<\/p>\n<pre class=\"prettyprint\"><code>s = {'a', 'b', 'c'}\r\nfor v in s:\r\n  print(v)<\/code><\/pre>\n<h2 id=\"deep-dive\">Advanced: Enumerate Deep Dive<\/h2>\n<p>In Python, the <span class=\"symbol\">enumerate<\/span> function returns a Python object of type <span class=\"symbol\">enumerate<\/span><\/p>\n<p>Yes, there is an <strong>enumerate<\/strong> built-in function and an <strong>enumerate<\/strong> object \ud83d\ude42<\/p>\n<pre class=\"prettyprint\"><code>&gt;&gt;&gt; type(enumerate([1, 2, 3]))\r\n&lt;class 'enumerate'&gt;<\/code><\/pre>\n<p>Now <a href=\"https:\/\/github.com\/python\/cpython\/blob\/master\/Objects\/enumobject.c\" target=\"_blank\" rel=\"noopener noreferrer\">let&#8217;s go to Github<\/a> and check how the <strong>enumerate<\/strong> object is implemented.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"post-img alignnone wp-image-845 size-full\" src=\"http:\/\/www.afternerd.com\/blog\/wp-content\/uploads\/2018\/06\/Screen-Shot-2018-06-24-at-7.46.07-PM.png\" alt=\"github-enumerate\" width=\"1914\" height=\"1184\" srcset=\"https:\/\/www.afternerd.com\/blog\/wp-content\/uploads\/2018\/06\/Screen-Shot-2018-06-24-at-7.46.07-PM.png 1914w, https:\/\/www.afternerd.com\/blog\/wp-content\/uploads\/2018\/06\/Screen-Shot-2018-06-24-at-7.46.07-PM-300x186.png 300w, https:\/\/www.afternerd.com\/blog\/wp-content\/uploads\/2018\/06\/Screen-Shot-2018-06-24-at-7.46.07-PM-768x475.png 768w, https:\/\/www.afternerd.com\/blog\/wp-content\/uploads\/2018\/06\/Screen-Shot-2018-06-24-at-7.46.07-PM-1024x633.png 1024w, https:\/\/www.afternerd.com\/blog\/wp-content\/uploads\/2018\/06\/Screen-Shot-2018-06-24-at-7.46.07-PM-200x124.png 200w, https:\/\/www.afternerd.com\/blog\/wp-content\/uploads\/2018\/06\/Screen-Shot-2018-06-24-at-7.46.07-PM-400x247.png 400w, https:\/\/www.afternerd.com\/blog\/wp-content\/uploads\/2018\/06\/Screen-Shot-2018-06-24-at-7.46.07-PM-600x371.png 600w, https:\/\/www.afternerd.com\/blog\/wp-content\/uploads\/2018\/06\/Screen-Shot-2018-06-24-at-7.46.07-PM-800x495.png 800w, https:\/\/www.afternerd.com\/blog\/wp-content\/uploads\/2018\/06\/Screen-Shot-2018-06-24-at-7.46.07-PM-1200x742.png 1200w\" sizes=\"(max-width: 1914px) 100vw, 1914px\" \/><\/p>\n<p>As you can see, the <span class=\"symbol\">enumerate<\/span> object stores an index <span class=\"symbol\">en_index<\/span>, an iterator <span class=\"symbol\">en_sit<\/span>, and a result tuple <span class=\"symbol\">en_result<\/span><\/p>\n<p><span class=\"symbol\">en_sit<\/span> is actually the input parameter that we passed to the <strong>enumerate<\/strong> function.<\/p>\n<p>It must be an <strong>iterable<\/strong> object.<\/p>\n<p>At a given index, the result is a tuple of two elements.<\/p>\n<p>The first element is the index and the second one is the item in <span class=\"symbol\">en_sit<\/span> with that index.<\/p>\n<p><span class=\"symbol\">enumerate<\/span> objects themselves are also iterables with each item being the mentioned result tuple.<\/p>\n<pre class=\"prettyprint\"><code>&gt;&gt;&gt; list(enumerate(['a', 'b', 'c']))\r\n[(0, 'a'), (1, 'b'), (2, 'c')]<\/code><\/pre>\n<p>That&#8217;s why when we iterate over the enumerate object with a for loop like this:<\/p>\n<pre class=\"prettyprint\"><code>&gt;&gt;&gt; for idx, val in enumerate(['a', 'b']):\r\n...   print(idx, val)\r\n...\r\n0 a\r\n1 b<\/code><\/pre>\n<p>We are effectively unpacking these tuples to an index and a value.<\/p>\n<p>But there is nothing that prevents you from doing this (but don&#8217;t do it :))<\/p>\n<pre class=\"prettyprint\"><code>&gt;&gt;&gt; for i in enumerate(['a', 'b']):\r\n...   print(i[0], i[1])\r\n...\r\n0 a\r\n1 b<\/code><\/pre>\n<p>Finally, have fun enumerating \ud83d\ude42<\/p>\n<h3>Learning Python?<\/h3>\n<p>Check out <a href=\"https:\/\/courses.afternerd.com\/\">the Courses section!<\/a><\/p>\n\n<h2>Featured Posts<\/h2>\n<ul>\n<li><a href=\"https:\/\/www.afternerd.com\/blog\/learn-python\/\">The Python Learning Path (From Beginner to Mastery)<\/a><\/li>\n<li><a href=\"https:\/\/www.afternerd.com\/blog\/learn-computer-science\/\">Learn Computer Science (From Zero to Hero)<\/a><\/li>\n<li><a href=\"https:\/\/www.afternerd.com\/blog\/coding-interview\/\">Coding Interview Preparation Guide<\/a><\/li>\n<li><a href=\"https:\/\/www.afternerd.com\/blog\/stock-investing-for-beginners\/\">The Programmer&#8217;s Guide to Stock Market Investing<\/a><\/li>\n<li><a href=\"https:\/\/www.afternerd.com\/blog\/start-programming-blog\/\">How to Start Your Programming Blog?<\/a><\/li>\n<\/ul>\n<div class=\"after-post-box\">\n<h2>Are you Beginning your Programming Career?<\/h2>\n<h3>I provide my best content for beginners in the newsletter.<\/h3>\n<ul>\n<li>Python tips for beginners, intermediate, and advanced levels.<\/li>\n<li>CS Career tips and advice.<\/li>\n<li>Special discounts on my premium courses when they launch.<\/li>\n<\/ul>\n<p>And so much more&#8230;<\/p>\n<h3>Subscribe now. It&#8217;s Free.<\/h3>\n<p><script type=\"text\/javascript\" src=\"\/\/mautic.afternerd.com\/form\/generate.js?id=2\"><\/script><\/p>\n<\/div>\n\n","protected":false},"excerpt":{"rendered":"","protected":false},"author":1,"featured_media":823,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[12],"tags":[13],"yst_prominent_words":[650,648,638,633,618,620,628,624,649,644,629,641,632,192,225,586,625,646,645,626],"_links":{"self":[{"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/posts\/806"}],"collection":[{"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/comments?post=806"}],"version-history":[{"count":28,"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/posts\/806\/revisions"}],"predecessor-version":[{"id":1650,"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/posts\/806\/revisions\/1650"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/media\/823"}],"wp:attachment":[{"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/media?parent=806"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/categories?post=806"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/tags?post=806"},{"taxonomy":"yst_prominent_words","embeddable":true,"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/yst_prominent_words?post=806"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}