Python List index Function

This python function is used to find the index of an item from a given list. In this section, we discuss how to use index method with practical examples, and its syntax is

list.index(list_item)

Python index List Function Example

It finds the index of an item from a given List, and the below code finds the position of 10 and 50 from integer items.

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

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

In this function example, we declared a string List. Next, we used this function to find the 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 List index function is another example of returning the 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

Example 2

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

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 find the index position of a specified word.

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

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