Python enumerate() Method
The enumerate()
is a constructor method returns an object of the enumerate
class for the given iterable, sequence, iterator, or object that supports iteration.
The returned enumerate object contains tuples for each item in the iterable that includes an index and the values obtained from iterating over iterable.
Syntax:
enumerate(iterable, start=0)
Parameters:
- iterable: The iterable to which the enumerator has to be added.
- start: (Optional) The starting index. Default is 0.
Return Value:
Returns an enumerate
object.
The following example gets an object of the enumerate class for the list and converts enumerate to list.
cities = ['Delhi','Chicago','New York']
enum = enumerate(cities)
print(type(enum))
enumlist = list(enum)
print(enumlist)
<type 'enumerate'>
[(0, 'Delhi'), (1, 'Chicago'), (2, 'New York')]
In the above example, the default index starts from 0, but we can change the initial counter to any number.
cities = ['Delhi','Chicago','New York']
enum = enumerate(cities, start=5)
print(list(enum))
[(5, 'Delhi'), (6, 'Chicago'), (7, 'New York')]
The enumerate()
function can be used with loops as follows.
for index, city in enumerate(cities):
print(index,city)
0 Delhi
1 Chicago
2 New York
The for-in loop above calls enumerate's __next__()
method that removes and returns each element, as shown below.
cities = ['Delhi','Chicago','New York']
enum = enumerate(cities)
print(enum.__next__())
print(enum.__next__())
print(enum.__next__())
(0, 'Delhi')
(1, 'Chicago')
(2, 'New York')