Python – Get Index of Item In List

Python List is a popular object and variable type which stores multiple values in a single variable. The list stores items in an indexed way where every item has an index number. But this index number is not set explicitly and created automatically in the background during the list creation, add or remove item operations. The index numbers can be used to get or return a specific item from the list.

index() Syntax

The index() method is used to return index number of the specified item from the list. The index() method syntax is like below.

LIST.index(ITEM,START,END)
  • LIST is the list we want to search.
  • ITEM is the item value or data we want to search index for.
  • START is the start index number for the ITEM search. This parameter is optional.
  • END is the end index number for the ITEM search. This parameter is optional.

Find Index Number of Item with index() Method

The Python List provides the index() method which can return the index number of the specified item. The item can be a string, integer, floating-point, or even a class object.

names = [ "ismail" , "ahmet" , "elif" , "ali" ]

i = names.index("ahmet")

print("The index of the \"ahmet\" is ",i)

Find Index Number of Item with After Specified Position

The index() method can also search for a given item after a specified position. If the item is before the specified position its index does not return. The position will be specified as an index.

names = [ "ismail" , "ahmet" , "elif" , "ali" , "ismail" , "ahmet" , "elif" ]

i = names.index("ahmet",2)

print("The index of the \"ahmet\" is ",i)

The output will be like below. Even there is an “ahmet” item at the index 1 it will returned because the start position is index number 2.

The index of the "ahmet" is 5

Find Index Number of Item with Before Specified Position

In order to get an item index number the before specified position can be returned by specifying the index number. We will also specify the start index number which can be set as 0 if we want to start from the begging of the list.

names = [ "ismail" , "ahmet" , "elif" , "ali" , "ismail" , "ahmet" , "elif" ]

i = names.index("ahmet", 0 , 4 )

print("The index of the \"ahmet\" is ",i)

The output will be like below.

The index of the "ahmet" is 1

Get Index Number For Non Existing Item

In some cases, the item we are searching for does not exist in the given list. When we use the index() method to return its index as a non-existing item it will return “ValueError: ‘mehmet’ is not in list” error.

names = [ "ismail" , "ahmet" , "elif" , "ali" ]

i = names.index("mehmet")

print("The index of the \"mehmet\" is ",i)

The output will be like below.

ValueError: 'mehmet' is not in list

Leave a Comment