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:

  1. iterable: The iterable to which the enumerator has to be added.
  2. 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.

Example: enumerate()
cities = ['Delhi','Chicago','New York']
enum = enumerate(cities) 
print(type(enum))

enumlist = list(enum)
print(enumlist)
Output
<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.

Example: enumerate()
cities = ['Delhi','Chicago','New York']
enum = enumerate(cities, start=5)
print(list(enum))
Output
[(5, 'Delhi'), (6, 'Chicago'), (7, 'New York')]

The enumerate() function can be used with loops as follows.

Example: Use enumerate() in Loop
for index, city in enumerate(cities):
    print(index,city)
Output
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.

Example: __next__()
cities = ['Delhi','Chicago','New York']
enum = enumerate(cities)
print(enum.__next__())
print(enum.__next__())
print(enum.__next__())
Output
(0, 'Delhi')
(1, 'Chicago')
(2, 'New York')