How to find the index of an item in a list in python?

A list is a sequence of data items enclosed within square brackets separated by commas. The data items in the list are indexed. In python, the index value starts from 0.

Consider a list list_1 = [3, 4, 6, 7, 4, 1, 3, 5, 2, 8]. The index value of element 5 is 7. This article discusses different ways to find the index value of an element in python.

index-list-python-questions

Python has an inbuilt index() method that returns the index value of a specified data item. If there are duplicate elements present in the list, the index() method returns the index value of the specified data item that is first encountered.

The index() method takes three parameters, element, start and stop. By default the value of start is 0 and stop is the length of the list. The index() starts searching from the starting index and stops searching at the ending index value.

The syntax for the index() method is given below.

#syntax:
list.index(element, start, end)

For example, consider a list list_1 = [2, 4, "apple", 3, 4, 6.7, "red"]. The index value of element 4 is 1. In the list_1 the element 4 is present at positions 1 and 4. But, the index() method returns the index 1 in which element 4 is first encountered.

list_1 = [2, 4, "apple", 3, 4, 6.7, "red"]
print("list_1 : ", list_1)
pos = list_1.index(4)
print("The index of element 4 : ", pos)

The above code returns the output as

list_1 = [2, 4, "apple", 3, 4, 6.7, "red"]
print("list_1 : ", list_1)
pos = list_1.index(4)
print("The index of element 4 : ", pos)
If an element passed as a parameter to the index() function is not present in the list it raises a ValueError.

In the following example, element 8 is not present in list_1. When passed as an argument to the index() function, it raises the ValueError exception.

list_1 = [2, 4, "apple", 3, 4, 6.7, "red"]
print("list_1 : ", list_1)
pos = list_1.index(8)
print("The index of element 4 : ", pos)

Output

 pos = list_1.index(8)
ValueError: 8 is not in list

Consider a list list_1 = [2, 4, "apple", 3, 4, 6.7, "red"]. A for loop iterates over the list, if the element is found at a position the index value is printed as output, and the break statement passes the control out of the loop. If the element is not found, the program returns the output as the Element not found.

list_1 = [2, 4, "apple", 3, 4, 6.7, "red"]
print("list_1 : ", list_1)
flag = 0
for i in range(len(list_1)):
    if list_1[i] == 4:
        print("The index of element 4 : ", i)
        flag = 1
        break
if flag == 0:
    print("Element not found")

Output

list_1 :  [2, 4, 'apple', 3, 4, 6.7, 'red']
The index of element 4 :  1
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions