Finding the index of an element by its value in Python
If we need to find an element in a list and get its index, we use the index method. We pass the element value to its first parameter. In the second and third optional parameters, we can specify the start and end of the search, respectively.
Let's find the index 1 from our list:
lst = [1, 2, 3]
print(lst.index(1)) # 0
Now let's set the start and end of the search for the element:
lst = [1, 2, 3, 1, 4]
print(lst.index(1, 2, 4)) # 3
If the element is not in the list, the index method will return an error:
lst = [1, 2, 3]
print(lst.index(4)) # will display an error
Given a list:
lst = ['a', 'b', 'c', 'd', 'e']
Find the element number with value 'c'.
Given a list:
lst = ['a', 'b', 'c', 'b', 'd']
Find the number of the second element with value 'b'.
The following code is given:
lst = ['ab', 12, 'cd', 34]
tst = 'cd'
print(lst.index(tst))
Tell me what will be output to the console.
The following code is given:
lst = [1, 3, 'a', 'b', 3, 6]
tst = 2
print(lst.index(tst))
Tell me what will be output to the console.