Python enumerate() function
 

Python enumerate() function

 

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.

Previous Python Iterator vs Iterable
Next Python map() function
 

About author

You might also like

Python Programming 0 Comments

Keywords In Python

Like other programming languages, Python also has some reserved words whose meaning is already defined by the Python interpreter these reserved words are known as Keywords. A keyword cannot be

Programming 0 Comments

Best 7 Python IDEs And Code Editors

A code editor basically used to write and edit code it is usually lightweight and considered good for learning and small projects. Once you start writing code for larger applications

Python Programming 0 Comments

Taking Input From Users In Python

Computer programs often need to interact with users to get some kind of data from them. Later this data is processed and output is displayed on the console. For example,

0 Comments

No Comments Yet!

You can be first to comment this post!

Leave a Reply