Enumerate is a built-in function of Python. It allows us to loop over something and have an automatic counter. Enumerate() method adds a counter to an iterable and returns it in a form of enumerate object. This enumerate object can then be used directly in for loops or be converted into a list of tuples using list() method.

Syntax

The enumerate() method takes two parameters. Syntax is

enumerate(iterable, start=0)
  • iterable – A sequence, an iterator, or objects that supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count from start and the values obtained from iterating over iterable.
  • start (optional) – enumerate() starts counting from this number. If start is omitted, 0 is taken as start.

It adds counter to an iterable and returns it. The returned object is an enumerate object.

Example

Below code shows the usage of enumerate().

l1 = ["eat","sleep","repeat"] 
s1 = "hello"

# 1. Printing the tuples 
for ele in enumerate(l1): 
  print (ele)

# Output
# (0, 'eat')
# (1, 'sleep')
# (2, 'repeat')

# 2. Set start index to 2 
print (list(enumerate(s1,2)))

# Output
# [(2, 'h'), (3, 'e'), (4, 'l'), (5, 'l'), (6, 'o')]

# 3. Use in Loop
grocery = ['bread', 'milk', 'butter']
for count, item in enumerate(grocery):
  print(count, item)

# Output
# 0 bread
# 1 milk
# 2 butter