Python enumerate()

The enumerate() in Python is a built-in function that adds a counter as a key to an iterable object (list, tuple, etc.) and returns an enumerating object.

enumerate() Syntax 

The syntax of enumerate() is:

enumerate(iterable, start=0)

enumerate() Parameters

The enumerate() function takes two parameters.

  • iterable – any object that supports iteration. E.g.:- list, tuple, etc.
  • start (optional) – the index value from which the counter needs to be started. If not specified, the default value is taken as 0

enumerate() Return Value

The enumerate() method adds a counter as a key to an iterable object (list, tuple, etc.) and returns an enumerating object.

The enumerated object can then be used directly for loops or converted into lists and tuples using the list() and tuple() method. 

Example 1: How enumerate() method works in Python?

# Python program to illustrate enumerate function

fruits = ['apple', 'orange', 'grapes','watermelon']
enumeratefruits = enumerate(fruits)

# check the type of object

# converting to list

# changing the default from 0 to 5
enumeratefruits = enumerate(fruits, 5)


<class 'enumerate'>
[(0, 'apple'), (1, 'orange'), (2, 'grapes'), (3, 'watermelon')]
[(5, 'apple'), (6, 'orange'), (7, 'grapes'), (8, 'watermelon')]

Example 2: Using Enumerate object in loops

# Python program to illustrate enumerate function in loops

lstitems = ["Ram","Processor","MotherBoard"]

# printing the tuples in object directly
for ele in enumerate(lstitems):
	print (ele)


# changing index and printing separately
for count,ele in enumerate(lstitems,100):
	print (count,ele)


#getting desired output from tuple
for count,ele in enumerate(lstitems):
    print(count, ele)


(0, 'Ram')
(1, 'Processor')
(2, 'MotherBoard')

100 Ram
101 Processor
102 MotherBoard

0 Ram
1 Processor
2 MotherBoard
Leave a Reply

Your email address will not be published. Required fields are marked *

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like
Python Type()

Python type()

Table of Contents Hide type() Syntaxtype() Parameterstype() Return ValueDifference between type() function and isinstance() functionExample of isinstance() method in PythonExample 1: Finding the type of a Python objectExample 2: type()…
View Post