Python: Find the index of an item in a list

Given a Python list, we have to find the index of an item in a list.
Submitted by Nijakat Khan, on July 15, 2022

To find the index of the specific element from the list, we can use the following methods:

1) Using index() Method

The index() method is used to find the index value of the specific element.

Syntax:

list_name.index(item)

It will print the index value of an item from the list_name.

Example 1:

# list
list = ["Gwalior", "Bhopal", "Indore", "Noida", "Delhi", "Ajmer"]

# Now, using the index() to get the index 
# of "Inodre"
Index_Value = list.index("Indore")

# Printing the index
print(Index_Value)  

Output:

2

2) Using for Loop

The for loop is used to iterate the sequence of elements (list, tuple, dictionary, etc.). Here, we can also define the range in for loop its syntax is different from the for loop of c programming language but can say that it is like for each loop.

Syntax:

for variable in sequence:
    # Loop operations

# or
for a in range(length):
    # Loop operations

Example 2:

# list
l=["Gwalior","Delhi", "Bhopal", "Indore", "Noida", "Delhi", "Ajmer"]

# Using for loop to get the index
for i in range(len(l)):
    if l[i]=="Delhi":
        # if element found, then
        # print the index
        print(i)

Output:

1
5

Note: The index() can return only one value and the for loop can return multiple values/index.

Suppose you have a list containing "Delhi" two times. Now you have to search the both index of "Delhi" then you cannot search with the help of the single index() function. For that, we use the for loop. When a list contains two "Delhi" then the index() finds the "Delhi" when found it will end itself, and will not search for further elements but in the second method, it will start checking from starting to last element even the "Delhi" is found or not when "Delhi" found then it will not stop it will check the further element.

Python List Programs »



Related Programs



Comments and Discussions!

Load comments ↻





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