Python List index Function

Python index List is used to find the index of an item from a given list. In this section, we discuss how to use this function with practical examples. The syntax of the Python list index function is

list.index(list_item)

Python index List Function Example

The list index function finds the index of an item from a given List. The below code finds the index position of 10 and 50 from an integer list.

a = [20, 30, 10, 40, 10, 50, 20]

print(a.index(10))
print(a.index(50))
2
5

In this List functions example, we declared a string List. Next, we used the index function to find the index position of Orange and Kiwi.

Fruits = ['Apple', 'Orange', 'Banana', 'Kiwi', 'Grape']

print("Orange = ", Fruits.index('Orange'))
print("Kiwi = ", Fruits.index('Kiwi'))
Orange =  1
Kiwi =  3

This Python List index function is another example to return the index position.

Fruits = ['Apple', 'Orange', 'Banana', 'Kiwi', 'Grape', 'Blackberry']
numbers = [9, 4, -5, 0, 22, -1, 2, 14]

print(Fruits)
print(numbers)
print()

print('Kiwi = ', Fruits.index('Kiwi'))
print('Orange = ', Fruits.index('Orange'))
print('Grape = ', Fruits.index('Grape'))

print()
print('0 = ', numbers.index(0))
print('2 = ', numbers.index(2))
print('-1 = ', numbers.index(-1))
['Apple', 'Orange', 'Banana', 'Kiwi', 'Grape', 'Blackberry']
[9, 4, -5, 0, 22, -1, 2, 14]

Kiwi =  3
Orange =  1
Grape =  4

0 =  3
2 =  6
-1 =  5

index List Function Example

This list index program is the same as the first example. However, this time we are allowing the user to enter the length of a List. Next, we used For Loop to append those numbers to the Python list.

intIndexList = []
 
number = int(input("Please enter the Total Number of List Elements: "))
for i in range(1, number + 1):
    value = int(input("Please enter the Value of %d Element : " %i))
    intIndexList.append(value)
    
item = int(input("Please enter the Item that you want to Find: "))

print("The Index  Position of Given Item = ", intIndexList.index(item))
Python Index List Function 3

This program allows users to enter their own string or words and then finds the index position of a specified word.

strIndexList = []
 
number = int(input("Please enter the Total Number of List Elements: "))
for i in range(1, number + 1):
    value = input("%d Element : " %i)
    strIndexList.append(value)
    
item = input("Please enter the Item that you want to Find: ")

print("The Index  Position of Given Item = ", strIndexList.index(item))
Please enter the Total Number of List Elements: 4
1 Element : Apple
2 Element : Kiwi
3 Element : Banana
4 Element : Orange
Please enter the Item that you want to Find: Banana
The Index  Position of Given Item =  2