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:
pythonlst = [1, 2, 3]
print(lst.index(1)) # 0
Now let's set the start and end of the search for the element:
pythonlst = [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:
pythonlst = [1, 2, 3]
print(lst.index(4)) # will display an error
Задание 1
Given a list:
pythonlst = ['a', 'b', 'c', 'd', 'e']
Find the element number with value 'c'.
Задание 2
Given a list:
pythonlst = ['a', 'b', 'c', 'b', 'd']
Find the number of the second element with value 'b'.
Задание 3
The following code is given:
pythonlst = ['ab', 12, 'cd', 34]
tst = 'cd'
print(lst.index(tst))
Tell me what will be output to the console.
Задание 4
The following code is given:
pythonlst = [1, 3, 'a', 'b', 3, 6]
tst = 2
print(lst.index(tst))
Tell me what will be output to the console.