/    /  Python – Enumerate

Python Enumerate

In Python, Enumerator is a built-in function that adds a counter of iterative numbers. Enumerator can add counter to provided data structures like integers, characters, lists, strings and etc., If we do not provide any counter, then enumerator automatically starts from 0. If we provide any counter, then the iteration of the number starts from that respective counter. The return type of enumerate() function is enumerate object.


Syntax:

enumerate(iterable, start=0)


iterable– It can be a sequence, iterator or object which supports iteration.


Start– counting of the data structure starts from this number. Default value is 0.


Python Code:

week = ['Mon','Tue','Wed','Thu','Fri'] 

# creating enumerate objects 
obj = enumerate(week) 

print(list(enumerate(week,1)))
print("Return type of obj is: ",type(obj))


Output:

[(1, ‘Mon’), (2, ‘Tue’), (3, ‘Wed’), (4, ‘Thu’), (5, ‘Fri’)]

Return type of obj is:  <class ‘enumerate’>


Using Enumerate in loops

enumerate() function can be used in loops. It will count the data structure in a loop by starting with a number provided by the user.


Python Code:

week = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
obj = enumerate(week)

for item in obj:
    print(item)
    
for count,item in enumerate(week,100): 
    print(count,item)


Output:

(0, ‘Mon’)

(1, ‘Tue’)

(2, ‘Wed’)

(3, ‘Thu’)

(4, ‘Fri’)

100 Mon

101 Tue

102 Wed

103 Thu

104 Fri