Python: enumerate() function
enumerate() function
The enumerate() function returns an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration.
Note: The __next__() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable.
Version:
(Python 3)
Syntax:
enumerate(iterable, start=0)
Parameter:
Name | Description |
---|---|
iterable | A sequence, an iterator, or some other object which supports iteration |
start | A Number. Defining the start number of the enumerate object. Default 0.If start is omitted, 0 is taken as start. |
Return value:
Return an enumerate object.
Example: Python enumerate() function
<<< seasons = ['Spring', 'Summer', 'Fall', 'Winter']
<<< list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
<<< list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
Equivalent to:
def enumerate(sequence, start=0):
n = start
for elem in sequence:
yield n, elem
n += 1
Example: Python enumerate() function
fruits = ['Mango', 'Apple', 'Orange', 'Peach']
print(list(enumerate(fruits)))
print(list(enumerate(fruits, start=1)))
Output:
[(0, 'Mango'), (1, 'Apple'), (2, 'Orange'), (3, 'Peach')] [(1, 'Mango'), (2, 'Apple'), (3, 'Orange'), (4, 'Peach')]
Example:
Fruits = ['Apple', 'Mango', 'Orange']
enumerateFruits = enumerate(Fruits)
print(type(enumerateFruits))
# converting to list
print(list(enumerateFruits))
# changing the default counter
enumerateFruits = enumerate(Fruits, 10)
print(list(enumerateFruits))
Output:
<class 'enumerate'> [(0, 'Apple'), (1, 'Mango'), (2, 'Orange')] [(10, 'Apple'), (11, 'Mango'), (12, 'Orange')]
Example: Looping Over an Enumerate object
Fruits = ['Apple', 'Mango', 'Orange']
for item in enumerate(Fruits):
print(item)
print('\n')
for count, item in enumerate(Fruits):
print(count, item)
print('\n')
# changing default start value
for count, item in enumerate(Fruits, 50):
print(count, item)
Output:
(0, 'Apple') (1, 'Mango') (2, 'Orange') 0 Apple 1 Mango 2 Orange 50 Apple 51 Mango 52 Orange
Python Code Editor:
Previous: divmod()
Next: eval()
Test your Python skills with w3resource's quiz
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python/built-in-function/enumerate.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics