Find the index of an element in a list using enumerate – Pythonic approach

In this article, we shall see how to get the index of each element in a list using the enumerate method in a more pythonic way. There are various methods available to get the index of an element in a list. Let us see all those methods to get a better idea and usage of the enumerate method.

Enumerate() in Python

A lot of times when dealing with iterators, we also get a need to keep a count of iterations. Python eases the programmers’ task by providing a built-in function enumerate() for this task.


The enumerate () method adds a counter to an iterable and returns it in a form of enumerate object. This enumerate object can then be used directly in for loops or be converted into a list of tuples using list() method.

enumerate in python

The output of the above program is,

Return type: < type 'enumerate' >
[(0, 'eat'), (1, 'sleep'), (2, 'repeat')]
[(2, 'g'), (3, 'e'), (4, 'e'), (5, 'k')]

Let us look at the traditional methods. There are two types of methods to get the index.

  1. Using range() method to get the index manually.
  2. Using index method to get the index.

Using range() method

In this method we shall use the start value as 0 and the end value as the length of the list and iterate over a for loop to get the index value and also the element present in the index. This is the worst and naive method to use for anyone except for beginners.

range method to get index

The output of this code is,

0 1
1 2
2 4

Using index() method

In this method we make use of the index() method of the list data type to get the index and the value of the element present in that index. This is a better approach compared to the previous method but not good enough.

using index method to get the index and value

Using enumerate to get index

Finally, we are going to use the enumerate method in the following example to get the index and the value of the element present in that index.

As mentioned above enumerate takes an iterator and returns an enumerate object. For each value in an iterator a tuple is generated. The tuple consists of two values one the index and the other the value itself.

enumerate method to get the index

The output of the above code is,

0 1
1 2
2 4
3 9
4 5

If you do not want to begin your index value from 0 you can also specify the starting value by passing it as an additional argument to the enumerate method.

Let us say i want to start by index numbering from 10. Then I can do this.

enumerate method with index starting value specified

The output of this code is,

10 1
11 2
12 4
13 9
14 5

Conclusion

Hope this article is helpful. We can solve a problem by any number of ways. But, what matters the most is the way we solve it.

Happy coding!