Finding Index of List ElementsΒΆ

Lists have an index() method that accepts a single parameter. The method will return the index of the first occurrence of the supplied value within the list. If the value does not appear in the list, the method will produce an error.

The cell below creates a randomly generate list of 30 elements. Run this cell as is.

import random
random.seed(1)
rand_list = random.choices(range(0,50), k=30)
print(rand_list)
[6, 42, 38, 12, 24, 22, 32, 39, 4, 1, 41, 21, 38, 0, 22, 36, 11, 47, 45, 1, 1, 27, 46, 19, 10, 21, 1, 11, 21, 24]

The value 1 appears multiple times in this list. The code in the cell below will return the index of the first occurrence of 1.

rand_list.index(1)
9

The value 2 does not appear in the list. The code below will result in an error.

rand_list.index(2)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-3-53064462ac96> in <module>
----> 1 rand_list.index(2)

ValueError: 2 is not in list