What is list.index() in Python?

Among the many list methods in Python is the list.index() method. The list.index() method is used to check for the existence of an item in a list.

Syntax

list.index(element)

Parameters

element: This is a required value of the element of the list of which its index is to be searched for.

Example 1

Let’s find the index of the element of a list of even numbers up to ten.

even_numbers = [2, 4, 6, 8, 10]
# to find the index of 2 in the list
index = even_numbers.index(2)
print(f'the index of 2 in the list is {index}')
# to find the index of 10 in the list
index = even_numbers.index(10)
print(f'the index of 10 jn the list is {index}')

Explanation

  • Line 1: We create a list of even numbers up to ten.

  • Line 4: We create a variable called index to return the index value of the number 2 present in the list using even_numbers.index(2).

  • Line 5: We return the output of the index variable.

  • Line 8: We did the same thing we did on line 4, but this time we checked for the index of the number 10 in the list.

  • Line 9: We returned the output of the index variable.

Example 2

Let’s see if we can find the index of an element not present in a list of the countries provided below.

countries = ['Germany', 'France', 'Canada', 'Tunisia','China']
index= countries.index('Angola')
print(index)

The code above returned a ValueError. This is simply because Angola is not present in the list provided.

Free Resources