How to find index of a list item in python ?

Published: January 30, 2019

Updated: March 21, 2023

Tags: Python; List;

DMCA.com Protection Status

The index of a list item in Python can be found using the index() method. This method takes an element as an argument and returns its position in the list. The syntax for the method is myList.index(element).

Find index when item is unique

For example, if you have a list of random numbers:

import random

myList = [random.randint(0,5) for i in range(10)]

output

[1, 0, 4, 4, 4, 4, 0, 2, 1, 0]

To find out the index of number 7, then your code should look something like this:

myList.index(2)

This would print out

 7

which is the index position of number 7 in our list. To confirm that it worked correctly, we can also check by printing the item at that index position:

print( myList[7] )

This would print out 2, which is the number we were looking for.

It is important to note that the index() method only works with lists and not other types of collections like dictionaries or tuples.

Find index when item is unique

Additionally, if there are multiple occurrences of an element in a list, then the index() method will return the position of its first occurrence.:

myList.index(4)

output

2

To find all the indexes of 4, a straightforward solution is to use Python's list comprehensions. With this method, you can quickly and efficiently identify every index containing the desired value!

[idx for idx,i in enumerate(myList) if i == 4]

output

[2, 3, 4, 5]

References

Links Site
index() docs.python.org