What are enumerations in Python?

An enumerate function keeps count of the number of iterations done.

Have you ever needed to loop over a list and know where you were at in the list? You could add a counter that would allow you to increment as you loop, or you could use Python’s built-in enumerate function.

The enumerate() method​ adds a counter to an iterable and returns it in the form of an enumerate (iterable) object, which can then also be used directly in for-loops.

Syntax

The syntax is as follows:

Code

Now,​ let’s take a look at an example that implements the enumerate() function.

#creating a list
mylist = ['alpha','bravo','charlie']
#myobj will be an enumerate object
myobj = enumerate(mylist); #start will have the default value of zero here
#prints the return type of myobj
print "Return type:",type(myobj)
#prints tuples containing the counter value and the corresponding element in the list
print list(myobj)
#myobj will be an enumerate object
myobj = enumerate(mylist,2); #starting index of the counter set to 2
#prints tuples with counter value starting from two this time
print list(myobj)

Now let’s use it in a for-loop!

#creating a list
mylist = ['alpha','bravo','charlie']
#using enumerate in for-loop
for ele in enumerate(mylist): #default counter value is set to zero
print ele
print "Setting starting counter value to 2"
#using enumerate in for-loop with the counter value set to 2
for ele in enumerate(mylist,2):
print ele
Copyright ©2024 Educative, Inc. All rights reserved