Python List index() Method

Python list index() method returns the index of the specified element in the list.

Syntax

list.index(element,start,end)

Parameters

  1. element(required): It is the item you are searching for in the list.
  2. start(optional): It starts searching from this index.
  3. end(optional): It is the position where the search ends.

Return value

This method returns the index of the given element in the list.

Example 1: How to Use list index() method

Visual Representation of How to Use list.index() method

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

print(elementIndex)

Output

1

Example 2: Using Start and End Parameters

Visual Representation of Working of an index() With Start and End Parameters

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

index = alphabets.index('k')

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

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

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

Output

The index of k: 0
The index of a: 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

Traceback (most recent call last):
File "app.py", line 2, in <module>
elementIndex = GoT.index('Arya')
ValueError: 'Arya' is not in list

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.