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)
This method takes a single argument:
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.
# 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
# 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
# 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