Tutorial Study Image

Python index()

The index() function in python helps to return the index of the given element in the list. We can also provide starting and ending point of the search through the list.

list.index(element, start, end) #where the element may be string, number, list, etc

index() Parameters:

This method takes three parameters. The output of this method should be an integer value indicating the position of the element.

Parameter Description Required / Optional
element the element to be searched Required
start start searching from this index Optional
end search the element up to this index Optional

index() Return Value

If the method found more than one matching of the given element, it will return only the index of the first occurrence.

Input Return Value
element index of element
if no element ValueError exception

Examples of index() method in Python

Example 1: How index() works in Python

# alphabet list
alphabet = ['a', 'b', 'c', 'e', 'd', 'e', 'f']

# index of 'c' in alphabet
indexpos = alphabet.index('c')
print('The index of c:', indexpos)

# element 'e' is searched
# index of the first 'e' is returned
indexpos = alphabet.index('e')

print('The index of e:', indexpos)


The index of c: 2
The index of e: 3

Example 2: Index() if the searched element not present in the List

# alphabet list
alphabet = ['a', 'b', 'c', 'd', 'e', 'f']

# index of'g' is alphabet
indexpos = alphabet.index('g')
print('The index of g:', indexpos)


ValueError: 'g' is not in list

Example 3: Working of index() by giving start and end parameters

# alphabets list
alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'd']

# index of 'c' in alphabets
indexpos = alphabets.index('c')   # 2
print('The index of c:', indexpos)

# 'd' after the 4th index is searched
indexpos = alphabets.index('i', 4)   # 7
print('The index of d:', indexpos)

# 'd' between 4rd and 6th index is searched
indexpos = alphabets.index('d', 4, 6)   # Error!
print('The index of d:', indexpos)


The index of c: 2
The index of d: 7
Traceback (most recent call last):
  File "*lt;string>", line 13, in 
ValueError: 'd' is not in list