Home » Python

Python List index() Method with Example

Python List index() Method: Here, we are going to learn how to find the index of the given element in a list?
Submitted by IncludeHelp, on December 03, 2019

List index() Method

index() method 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:

    list_name.index(element)

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:

# Python List index() Method with Example

# 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:

# Python List index() Method with Example

# 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

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.