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.
The syntax is as follows:
Now, let’s take a look at an example that implements the enumerate()
function.
#creating a listmylist = ['alpha','bravo','charlie']#myobj will be an enumerate objectmyobj = enumerate(mylist); #start will have the default value of zero here#prints the return type of myobjprint "Return type:",type(myobj)#prints tuples containing the counter value and the corresponding element in the listprint list(myobj)#myobj will be an enumerate objectmyobj = enumerate(mylist,2); #starting index of the counter set to 2#prints tuples with counter value starting from two this timeprint list(myobj)
Now let’s use it in a for
-loop!
#creating a listmylist = ['alpha','bravo','charlie']#using enumerate in for-loopfor ele in enumerate(mylist): #default counter value is set to zeroprint eleprint "Setting starting counter value to 2"#using enumerate in for-loop with the counter value set to 2for ele in enumerate(mylist,2):print ele