19
Python enumerate()
ItsMyCode |
The 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.
The syntax of enumerate()
is:
**enumerate(iterable, start=0)**
The enumerate()
function takes two parameters.
- iterable – any object that supports iteration. E.g.:- list , tuple , etc.
- start (optional) – the index value from which the counter needs to be started. If not specified, the default value is taken as 0
The enumerate()
method adds a counter as a key to an iterable object ( list , tuple , etc.) and returns an enumerating object.
The enumerated object can then be used directly for loops or converted into lists and tuples using the 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))
Output
<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)
Output
(0, 'Ram')
(1, 'Processor')
(2, 'MotherBoard')
100 Ram
101 Processor
102 MotherBoard
0 Ram
1 Processor
2 MotherBoard
The post Python enumerate() appeared first on ItsMyCode.
19