enumerate() in python

Harshini Komali
2 min readJun 10, 2021

--

enumerate(iterable,start=0)

Suppose there is a python list fruits which is defined as

>> fruits= [‘apple’,’banana’,’orange’]

Oftentimes, while solving coding problems, you would require to maintain a dictionary or a tuple which stores the index of the element and the element as a pair. For example, we would like to maintain a tuple called fruits_pos which stores the index of the fruit in the list fruits declared above as well as its name as a pair shown below.

fruits_pos = ((0,’apple’),(1,’banana’),(2,’orange’))

To build a tuple like fruit_pos from the list fruits, you take and empty tuple fruit_pos initially and you add each (index,name) pair while looping over the list.

Instead, python has provided a built-in function called enumerate(). The function takes an iterator ,sequence or some other object which supports iteration as the first argument. It also has a second argument start which is optional. By default, start is set to 0 i.e. the index of the first element starts from 0. If you want your object’s index to start from 1, then you pas 1 as the second argument.

So when you call enumerate() on the list fruits declared above, the output would be an enumerated object which you can use by converting it to a list or a tuple or a dictionary of enumerated elements.

>> fruits = [‘apple’,’banana’,’orange’]
>> list(enumerate(fruits))
[(0,’apple’),(1,’banana’),(2,’orange)]
>> tuple(enumerate(fruits,1))
((0,’apple’),(1,’banana’),(2,’orange))

If you have to implement enumerate() from scratch on your own, the code is something like this:

def enumerate(fruits,start=0):
i = start
for element in fruits:
yield i,element
i = i + 1

If you want to use enumerate() in loops:

>> fruits = [‘apple’,’banana’,’orange’]
>> for fruit in enumerate(fruits):
... print(fruit)

Output:

(0,'apple')
(1,'banana')
(2,'orange')

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Harshini Komali
Harshini Komali

Written by Harshini Komali

Just another Software Engineer working on making myself a better engineer than yesterday.

No responses yet

Write a response