24
loading...
This website collects cookies to deliver better user experience
enumerate()
in Python is a built-in function that adds a counter as a key to an iterable object ( list , tuple , etc.) and returns an enumerating object.enumerate()
is:**enumerate(iterable, start=0)**
enumerate()
function takes two parameters.enumerate()
method adds a counter as a key to an iterable object ( list , tuple , etc.) and returns an enumerating object.list()
and tuple()
method. # Python program to illustrate enumerate function
fruits = ['apple', 'orange', 'grapes','watermelon']
enumeratefruits = enumerate(fruits)
# check the type of object
print(type(enumeratefruits))
# converting to list
print(list(enumeratefruits))
# changing the default from 0 to 5
enumeratefruits = enumerate(fruits, 5)
print(list(enumeratefruits))
<class 'enumerate'>
[(0, 'apple'), (1, 'orange'), (2, 'grapes'), (3, 'watermelon')]
[(5, 'apple'), (6, 'orange'), (7, 'grapes'), (8, 'watermelon')]
# Python program to illustrate enumerate function in loops
lstitems = ["Ram","Processor","MotherBoard"]
# printing the tuples in object directly
for ele in enumerate(lstitems):
print (ele)
print('\n')
# changing index and printing separately
for count,ele in enumerate(lstitems,100):
print (count,ele)
print('\n')
#getting desired output from tuple
for count,ele in enumerate(lstitems):
print(count, ele)
(0, 'Ram')
(1, 'Processor')
(2, 'MotherBoard')
100 Ram
101 Processor
102 MotherBoard
0 Ram
1 Processor
2 MotherBoard