Python enumerate()

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.


Syntax

It is equivalent to:


Return

It returns tuple with count and values obtained while iterating.


Example

Let’s understand with help of simple example:

lst = ['One','Two','Three'] for count,item in enumerate(lst): print(count) print (item)

Output:

0
One
1
Two
2
Three

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)

Output:

100 One
101 Two
102 Three

Another Example:

lst = ['One','Two','Three','Four'] for count,item in enumerate(lst,1): if(count==2): continue print(count," ",item)

Output:

1 One
3 Three
4 Four

As you can see, we have skipped iteration when count was 2.
That’s all about Python enumerate().

Leave a Reply

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