In this post, we will see about enumerate() function.
Python enumerate() method helps you to keep track of count while iterating.It is extremely helpful when you want to perform some operations based on count.It returns a tuple with count and values obtained from iterating over iterable.
It is equivalent to:
def enumerate(sequence, start=0):
n = start
for elem in sequence:
yield n, elem
n += 1
It returns tuple with count and values obtained while iterating.
Let’s understand with help of simple example:
lst = ['One','Two','Three'] for count,item in enumerate(lst): print(count) print (item)
enumerate with different start
You can pass optional attribute as start if you want to start counter from some other value.
lst = ['One','Two','Three'] for count,item in enumerate(lst,100): print(count," ",item)
lst = ['One','Two','Three','Four'] for count,item in enumerate(lst,1): if(count==2): continue print(count," ",item)
As you can see, we have skipped iteration when count was 2.
That’s all about Python enumerate().