Python List index: How to Search Element in the List

If any element which is not present is searched, then it returns the ValueError. The method index() returns the lowest index in the list that item appears.

Python List Index

Python list index() is an inbuilt function that searches an element in the list and returns its index. The list index() method returns the index of the element in the list.

Syntax

The syntax for the index() method is the following.

list.index(element)

Parameters

The element parameter is required and is searched for in the list.

Return value

The index() method returns the index of the given element in the list.

Example 1: How to Use list.index() method

GoT = ['Daenerys', 'Jon', 'Tyrion']
elementIndex = GoT.index('Jon')

print(elementIndex)

The index() method returns an index, and in the above example, it returns Jon’s index, which is 1.

Output

1

Example 2: Working of an index() With Start and End Parameters

alphabets = ['k', 'r', 'u', 'n', 'a', 'l']

index = alphabets.index('k')

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

index = alphabets.index('a', 3, 5)

print('The index of i:', index)

Output

The index of e: 0
The index of i: 4

Example 3: ValueError: ” is not in list

If we find an index of an element not present in the list, it will return a ValueError. Let us see the following code.

GoT = ['Daenerys', 'Jon', 'Tyrion']
elementIndex = GoT.index('Arya')

print(elementIndex)

Output

Originally published by Krunal at Appdividend

#python #python list index #valueerror

Python List index: How to Search Element in the List
104.65 GEEK