Python Enumerate Explained (With Examples)

How do I get the index of an element while I am iterating over a list?

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. 😓😓😓

Python gives you the luxury of iterating directly over the values of the list which is most of the time what you need.

However, there are times when you actually need the index of the item as well.

Python has a built-in function called enumerate that allows you to do just that.

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.

Jump directly to a specific section:

Enumerate a List

Let’s see what to do if we want to enumerate a python list.

You can iterate over the index and value of an item in a list by using a basic for loop

L = ['apples', 'bananas', 'oranges']
for idx, val in enumerate(L):
  print("index is %d and value is %s" % (idx, val))

The code above will have this output:

index is 0 and value is apples
index is 1 and value is bananas
index is 2 and value is oranges

How easy was that!

Now let’s see how to enumerate a tuple.

Enumerate a Tuple

Enumerating a tuple isn’t at all different from enumerating a list.

t = ('apples', 'bananas', 'oranges')
for idx, val in enumerate(t):
  print("index is %d and value is %s" % (idx, val))

And as you expect, the output will be:

index is 0 and value is apples
index is 1 and value is bananas
index is 2 and value is oranges

Now that you know how to enumerate a list and a tuple, how can you enumerate a list of tuples? 🤔🤔🤔

Enumerate a List of Tuples (The Neat Way)

Say you have a list of tuples where each tuple is a name-age pair.

L = [('Matt', 20), ('Karim', 30), ('Maya', 40)]

Of course one way to enumerate the list is like this:

for idx, val in enumerate(L):
  name = val[0]
  age = val[1]
  print("index is %d, name is %s, and age is %d" \
         % (idx, name, age))

The above code will definitely work and it will print out this output.

index is 0, name is Matt, and age is 20
index is 1, name is Karim, and age is 30
index is 2, name is Maya, and age is 40

However, a cleaner way to achieve this is through tuple unpacking

With tuple unpacking, we can do something like this

for idx, (name, age) in enumerate(L):
  print("index is %d, name is %s, and age is %d" \
        % (idx, name, age))

Enumerate a String

enumerate-string

So what happens when you use the enumerate function on a string object?

An item in a string is a single character.

So if you enumerate over a string, you will get back the index and value of each character in the string.

Let’s take an example:

str = "Python"
for idx, ch in enumerate(str):
  print("index is %d and character is %s" \
         % (idx, ch))

And the output will be:

index is 0 and character is P
index is 1 and character is y
index is 2 and character is t
index is 3 and character is h
index is 4 and character is o
index is 5 and character is n

Enumerate with a Different Starting Index

So as you know, indices in python start at 0.

This means that when you use the enumerate function, the index returned for the first item will be 0.

However in some cases, you want the loop counter to start at a different number.

enumerate allows you to do that through an optional start parameter.

For example, let’s say we want to enumerate over a list starting at 1.

The code will look like this:

L = ['apples', 'bananas', 'oranges']
for idx, s in enumerate(L, start = 1):
  print("index is %d and value is %s" \
         % (idx, s))

The above code will result in this output.

index is 1 and value is apples
index is 2 and value is bananas
index is 3 and value is oranges

Needless to say, you can also start with a negative number.

Why It doesn’t Make Sense to Enumerate Dictionaries and Sets

So does it make sense to use the enumerate function for dictionaries and sets?

Absolutely not!

Think about it, the only reason you would use enumerate is when you actually care about the index of the item.

Dictionaries and Sets are not sequences.

Their items do not have an index, and they don’t, by definition, need one.

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:

d = {'a': 1, 'b': 2, 'c': 3}
for k, v in d.items():
  # k is now the key
  # v is the value
  print(k, v)

And if you want to iterate over a set, then just use a regular for loop.

s = {'a', 'b', 'c'}
for v in s:
  print(v)

Advanced: Enumerate Deep Dive

In Python, the enumerate function returns a python object of type enumerate

Yes, there is an enumerate built-in function and an enumerate object 🙂

>>> type(enumerate([1, 2, 3]))
<class 'enumerate'>

Now let’s go to github and check how the enumerate object is implemented.

github-enumerate

As you can see, the enumerate object stores an index en_index, an iterator en_sit, and a result tuple en_result

en_sit is actually the input parameter that we passed to the enumerate function.

It must be an iterable object.

At a given index, the result is a tuple of two elements.

The first element is the index and the second one is the item in en_sit with that index.

enumerate objects themselves are also iterables with each item being the mentioned result tuple.

>>> list(enumerate(['a', 'b', 'c']))
[(0, 'a'), (1, 'b'), (2, 'c')]

That’s why when we iterate over the enumerate object with a for loop like this:

>>> for idx, val in enumerate(['a', 'b']):
...   print(idx, val)
...
0 a
1 b

We are effectively unpacking these tuples to an index and a value.

But there is nothing that prevents you from doing this (but don’t do it :))

>>> for i in enumerate(['a', 'b']):
...   print(i[0], i[1])
...
0 a
1 b

Finally, have fun enumerating 🙂

Learning Python?

If you are a beginner, then I highly recommend this book.

No longer a beginner?

Then you are ready for this book to get to the next level (It’s my favorite).

2018-11-19T01:08:01+00:00 By |

Leave A Comment