Python List Methods Tutorial: Python List Index()

The index() method searches an element in the list and returns its index.
In simple terms, the index() method finds the given element in a list and returns its position.

If the same element is present more than once, the method returns the index of the first occurrence of the element.

Note: Index in Python starts from 0, not 1.

The syntax of the index() method is:

list.index(element)

index() Parameters

This method takes a single argument:

  • element - element that is to be searched.

Return value from index()

The method returns the index of the element in the list.
If not found, it raises a ValueError exception indicating the element is not in the list.

Example 1: Find the position of an element in the list

# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']

# index of 'e'
index = vowels.index('e')
print('The index of e:', index)

# index of the first 'i'
index = vowels.index('i')
print('The index of i:', index)

Output

The index of e: 1
The index of i: 2

Example 2: Index of an element not present in the list

# vowels list
vowels = ['a', 'e', 'i', 'o', 'u']

# 'p' doesn't exist in the list
index = vowels.index('p')
print('The index of p:', index)

Output

ValueError: 'p' is not in list

Example 3: Find the index of tuple and list inside a list

# random list
random = ['a', ('a', 'b'), [3, 4]]

# index of ('a', 'b')
index = random.index(('a', 'b'))
print("The index of ('a', 'b'):", index)

# index of [3, 4]
index = random.index([3, 4])
print("The index of [3, 4]:", index)

Output

The index of ('a', 'b'): 1
The index of [3, 4]: 2
Python List Methods Tutorial: Python List Index()
1.45 GEEK