How to find index of a list item in python ?

Active January 30, 2019    /    Viewed 4021    /    Comments 0    /    Edit


Example of how to find index of an item from a list in python:

Create a list of random integers

Let's consider a list of random numbers:

>>> import random
>>> l = [random.randint(0,5) for i in range(10)]
>>> l
[1, 0, 4, 4, 4, 4, 0, 2, 1, 0]

Find index of an unique item

To find the position of 2, we can use the method index():

>>> l.index(2)
7

that returns 7.

Find indices of an item with duplicates

However if we use the method index() to retrieve indexes of 4, the method returns only the first index:

>>> l.index(4)
2

To retrieve all indexes of 4, a solution is to use the python list comprehensions:

>>> [idx for idx,i in enumerate(l) if i == 4]
[2, 3, 4, 5]

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount