Python List index() Method (with Examples)

Python List index() Method: In this tutorial, we will learn about the index() method of the list class with its usage, syntax, parameters, return type, and examples. By IncludeHelp Last updated : June 20, 2023

Python List index() Method

The index() is an inbuilt method of the list class that is used to get the index of the specified element, the method is called with this list and element can be supplied as an argument, it returns the index of the first occurrence of the element in the list.

Syntax

The following is the syntax of index() method:

list_name.index(element)

Parameter(s):

The following are the parameter(s):

  • element – It represents an element whose index to be found.

Return Value

The return type of this method is <class 'int'>, it returns an integer element that will the index of the first occurrence of the element, or it returns a ValueError if element does not exist in the list.

Example 1: Use of List index() Method

# declaring the list
cars = ["Porsche", "Audi", "Lexus", "Porsche", "Audi"]

# printing the list
print("cars: ", cars)

# finding index of "Porsche"
pos = cars.index("Porsche")
print("Porsche's index is:", pos)

# finding index of "Lexus"
pos = cars.index("Lexus")
print("Lexus's index is:", pos)

Output

cars:  ['Porsche', 'Audi', 'Lexus', 'Porsche', 'Audi']
Porsche's index is: 0
Lexus's index is: 2

Example 2: Use of List index() Method

If the specific element is not found in the list, the program returns a ValueError. The following program is demonstrating the same.

# declaring the lists
x = ["ABC", "XYZ", "PQR","ABC", "XYZ", "PQR"]
y = ["PQR", "MNO", "YXZ", "YXZ"]
z = ["123", "456", "789"]

# printing the findex of given element
print('x.index("ABC"):', x.index("ABC"))
print('y.index("YXZ"):', y.index("YXZ"))
print('z.index("789"):', z.index("789"))

# ValueError
print('x.index("MNO"):', x.index("MNO"))

Output

x.index("ABC"): 0
y.index("YXZ"): 2
z.index("789"): 2
Traceback (most recent call last):
  File "main.py", line 14, in <module>
    print('x.index("MNO"):', x.index("MNO"))
ValueError: 'MNO' is not in list

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.