Python enumerate() function


Gaming Laptop Series

Sometimes you may want to track the position of items in an iterable. You can do this in various ways, for example, you can create a counter variable and initialize it with zero now in every iteration increment the value of the counter variable, this will track the position of every item.

Python makes this easier for its user by providing an inbuilt function called enumerate(). In this article, we will discuss how you can use this function in your program.

The syntax of Python enumerate() function

The syntax of the Python enumerate() function is given below –

enumerate(iterable, start=0)

It takes two parameters i.e.

iterable – the first parameter is an iterable object such as list, tuple, etc

start – the start is the value of the counter from where it will start by default it is zero

Example and usage of Python enumerate() function

In the given example first, we use a counter variable and create a program to track the position of each item. We will use a print statement that will print the position and the item name. And later we will create the same program using enumerate() function in Python.

lst1= ['abc', 'bcd','cde', 'def', 'efg']
pos=0
for name in lst1:
   print(f'{pos} ==> {name}')
   pos+=1

Now see the output of this program in the given image –

The following example shows the use of enumerate() function in Python.

lst1= ['abc', 'bcd','cde', 'def', 'efg']
for pos,name in enumerate(lst1):
     print(f'{pos} ==> {name}')

When you run this program you will see the same output-

Now, what if you want to start the count from 10, pass the second parameter as 10. The complete code is given below.

lst1= ['abc', 'bcd','cde', 'def', 'efg']
for pos,name in enumerate(lst1,10):
    print(f'{pos} ==> {name}')

See the output in the given image –

Now you know how to use the Python enmuerate() function. If you have a query then write us in the comments below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.