Write a Python program to find the Index position of a specified element and print it. And if the specified element is not present then print -1 asthe result.Constraints:Input Format:<Read the List>Output Format:Integer valueExample:Input:['20','HTML','CSS','20','158']"HTML"Output:1Explanation:The List is - ['20','HTML','CSS','20','158']'20' => Index value 0'HTML' => Index value 1'CSS' => Index value 2'20' => Index value 3'158' =>Index value 4Value to search for is => HTMLWhich occupies the Index position 1
Question
Write a Python program to find the Index position of a specified element and print it. And if the specified element is not present then print -1 asthe result.Constraints:Input Format:<Read the List>Output Format:Integer valueExample:Input:['20','HTML','CSS','20','158']"HTML"Output:1Explanation:The List is - ['20','HTML','CSS','20','158']'20' => Index value 0'HTML' => Index value 1'CSS' => Index value 2'20' => Index value 3'158' =>Index value 4Value to search for is => HTMLWhich occupies the Index position 1
Solution
Here is a Python program that accomplishes the task:
def find_index(lst, element):
try:
index = lst.index(element)
except ValueError:
index = -1
return index
lst = ['20','HTML','CSS','20','158']
element = 'HTML'
print(find_index(lst, element))
This program defines a function find_index that takes a list and an element as arguments. It tries to find the index of the element in the list using the index method. If the element is not in the list, the index method raises a ValueError exception, which is caught and handled by setting index to -1. The function then returns index.
The list and element to search for are defined, and the function is called with these as arguments. The result is printed to the console.
Similar Questions
Write a Python program to find the Index position of a specified element and print it. And if the specified element is not present then print -1 as
Write a program to display elements from a given list present at even index positions.
Create a list num=[23,12,5,9,65,44].➢ Print the length of the list.➢ Print the elements from second to fourth position using positive indexing.➢ Print the elements from position third to fifth using negative indexing
What will be the output of the following code snippet?for index in range(20, 10, -3) :print(index, end = ' ')
What is the index of the first element in an array in Python?Options10-1Depends on the size of the array
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.