How To Enumerate In Python Programming Language? – POFTUT

How To Enumerate In Python Programming Language?


Python provides easy to use functions and mechanisms for programmers. While dealing with collection or list types we generally need some way to enumerate them. enumerate() function is used to create an iterable or enumerable type from the given list or collection. After this operation, we can use created object to iterate with for or while structures.

Enumerate

We will start with a simple enumerate example. We will provide a list named fruits to the enumerate() function which will change list with index numbered list in a tuple format.

fruits=['apple','lemon','cherry','orange'] 
list(enumerate(fruits))                    
#This will print

#[(0, 'apple'), (1, 'lemon'), (2, 'cherry'), (3, 'orange')]
Simply Enumerate
Simply Enumerate

Enumerate with Counter

We can specify the counter explicitly by specifying start parameter like below. As we can see in the following example the start index will be 1 not default 0 .

fruits=['apple','lemon','cherry','orange'] 
list(enumerate(fruits,start=1))  
#This will print          
# [(1, 'apple'), (2, 'lemon'), (3, 'cherry'), (4, 'orange')]
Enumerate with Counter
Enumerate with Counter

Get Index Values

As enumerate() functions returns in tuple format we can get index and item into separate variables and use them in a loop like below.

fruits=['apple','lemon','cherry','orange'] 
for index, item in enumerate(fruits): 
   print(index) 
   print(item)
Get Index Values
Get Index Values

LEARN MORE  Php - Array Variable Type

Leave a Comment