5 simple examples to learn python enumerate() function

In this Python tutorial we will concentrate on Python enumerate() function and it's usage with some simple and real time examples.

 

Python enumerate() function syntax

Sometimes, when we're looping over a container in a for loop, we want access to the index (the current position in the list) of the current item being processed. One way to handle this would be:

i = 0
for value in collection:
   # do something with value
   i += 1

Since this is so common, Python has a built-in function, enumerate(), which returns a sequence of (i, value) tuples, where the first object in each tuple is the index and the second is the original item.

for i, value in enumerate(collection):
   # do something with value

The general syntax of python enumerate() function:

enumerate(iterable, start=0)

Here,

  • iterable - must be a sequence, an iterator, or some other object that supports iteration
  • start (optional) - enumerate() starts counting from this number which defaults to 0 if not provided.

 

Example-1: Understanding how python enumerate() works

Let us take this simple example script which contains a list. I will iterate over the individual items of the list and then prepend index position number to each value. Normally I would write a code like this:

5 simple examples to learn python enumerate() function

Output from this script:

~]# python3 python-enumerate.py
0: ab
1: cd
2: ef

Now thanks to python enumerate() function, we can re-write the same code in more Pythonic way:

#!/usr/bin/env python3

mylist = ['ab', 'cd', 'ef'] ## List

for i, val in enumerate(mylist):
    print(f'{i}: {val}')

Output from this script:

 ~]# python3 python-enumerate.py
0: ab
1: cd
2: ef

So, the output is same from both the methods but in complex scenarios enumerate() can save you a bunch of line of codes.

 

Example-2: Add line number before starting of line in a file

In this python code I will open a file to read and prepend line number to each line and print the output. I am not modifying the content of the file though.

#!/usr/bin/env python3

import sys

## take the file as input argument
filename = sys.argv[1]

with open(filename) as myfile:
    for index, line in enumerate(myfile): 
        print(f"{index}: {line}", end="")

The enumerate() function returns a sequence of tuples, our for loop splits each tuple into two values, and the print statement formats them together.

Output from this script:

5 simple examples to learn python enumerate() function

As you see the counter value is added to each line. Since by default counter starts with 0, the line count is also starting from 0. If you wish to start the count by 1 then we have to make small modification to our code by using index+1. It adds one to the index for each line number, since enumerate, like all sequences, is zero-based.

#!/usr/bin/env python3

import sys

## take the file as input argument
filename = sys.argv[1]

with open(filename) as myfile:
    for index, line in enumerate(myfile): 
        ## using index+1 to start the count from 1
        print(f"{index+1}: {line}", end="")

Output from this script:

5 simple examples to learn python enumerate() function

So now the index value starts from 1 as expected.

 

Example-3: Create dictionary using enumerate()

When you are indexing data, a helpful pattern that uses enumerate is computing a dict mapping the values of a sequence (which are assumed to be unique) to their locations in the sequence:

#!/usr/bin/env python3

mycars = ['maruti', 'hyundai', 'honda']
mapping = {} ## empty dictionary

for index, value in enumerate(mycars):
    mapping[value] = index

print(mapping) ## content of mapping
print(type(mapping)) ## type of mapping

Output from this script:

~]# python3 python-enumerate-2.py
{'maruti': 0, 'hyundai': 1, 'honda': 2}
<class 'dict'>

 

Example-4: Print index and value as tuple

We have been modifying the output by separating the index and value, but if we just iterate over enumerate() then we get a tuple so no modification required and just a simple for loop would do the job.

#!/usr/bin/env python3

mylist = ['ab', 'cd', 'ef'] ## List

for val in enumerate(mylist):
    print(val)
    print(type(val))

Output from this script:

~]# python3 python-enumerate-3.py
(0, 'ab')
<class 'tuple'>
(1, 'cd')
<class 'tuple'>
(2, 'ef')
<class 'tuple'>

We could also get the output in list format:

#!/usr/bin/env python3

mylist = ['ab', 'cd', 'ef'] ## List

mynewlist = list(enumerate(mylist))
print(mynewlist)
print(type(mynewlist))

Output from this script:

~]# python3 python-enumerate-3.py
[(0, 'ab'), (1, 'cd'), (2, 'ef')]
<class 'list'>

 

Example-5: Define starting number to start the counting

By default we have seen that the counting of individual items start with 0, but we can define out own starting point using start=<num> where you can replace num with any integer value.
In the same example we used above, we will define a different starting number:

#!/usr/bin/env python3

mylist = ['ab', 'cd', 'ef'] ## List

mynewlist = list(enumerate(mylist, start=100))
print(mynewlist)
print(type(mynewlist))

Output from this script:

~]# python3 python-enumerate-3.py
[(100, 'ab'), (101, 'cd'), (102, 'ef')]
<class 'list'>

So, now our output contains a list where counting starts from 100 for first item and appends by 1 for each item in the list

 

Conclusion

In this tutorial we learned about the usage of python enumerate() function using different examples. The enumerate built-in function takes an iterable object as the input, and returns tuples consisting of a count plus a value. The actual returned enumerate object is iterable itself, so you can use it as you would any other iterator.

Leave a Comment

Please use shortcodes <pre class=comments>your code</pre> for syntax highlighting when adding code.