{"@context":"https://schema.org","@type":"Article","mainEntityOfPage":{"@type":"WebPage","@id":"https://www.tutorialsteacher.com/python/enumerate-method"},"headline":"Python enumerate() Method","author":{"@type":"Organization","name":"TutorialsTeacher","url":"https://www.tutorialsteacher.com/aboutus"},"publisher":{"@type":"Organization","name":"TutorialsTeacher","logo":{"@type":"ImageObject","url":"https://www.tutorialsteacher.com/Content/images/logo.svg"},"sameAs":["https://www.facebook.com/tutorialsteacher","https://twitter.com/tutorialstchr","https://www.youtube.com/@tutorialsteacherOfficial"]},"dateModified":"2021-06-26T15:03:44.1963265Z","description":"The enumerate() is a constructor method returns an object of the enumerate class for the given iterable, sequence, iterator, or object that supports iteration. "}enumerate class for the given iterable, sequence, iterator, or object that supports iteration. " />

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')
Want to check how much you know Python?