What is enumerate function
Enumerate function
hey @Pranav-Gupta-1716510788408154,
Python enumerate()
The enumerate() method adds counter to an iterable and returns it (the enumerate object).
The syntax of enumerate() is:
enumerate(iterable, start=0)
enumerate() Parameters
The enumerate() method takes two parameters:
- iterable - a sequence, an iterator, or objects that supports iteration
- start (optional) - enumerate() starts counting from this number. If start is omitted, 0 is taken as start (default).
Example:
#Creating a list named grocery
grocery = ['bread', 'milk', 'butter']
#Here start was taken as 0 as it's default value
enumerateGrocery = enumerate(grocery)
#This will return a enumerate object that will place a counter to those list items
# converting to list
print(list(enumerateGrocery))
# changing the default counter
enumerateGrocery = enumerate(grocery, 10)
print(list(enumerateGrocery))
Output:
[(0, 'bread'), (1, 'milk'), (2, 'butter')]
[(10, 'bread'), (11, 'milk'), (12, 'butter')]