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
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 as
Solution
Sure, here is a simple Python program that finds the index position of a specified element in a list. If the element is not present, it prints -1.
def find_index(lst, element):
try:
index = lst.index(element)
except ValueError:
index = -1
return index
# Test the function
lst = [1, 2, 3, 4, 5]
element = 3
print(find_index(lst, element)) # Output: 2
element = 6
print(find_index(lst, element)) # Output: -1
In this program, we define 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 we catch and assign -1 to the index. Finally, the function returns the index.
We then test the function with a list [1, 2, 3, 4, 5] and elements 3 and 6. The element 3 is in the list at index 2, so the function prints 2. The element 6 is not in the list, so the function prints -1.
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 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
What will be the output of the following code snippet?for index in range(20, 10, -3) :print(index, end = ' ')
Write a program to display elements from a given list present at even index positions.
What is the index of the first element in an array in Python?Options10-1Depends on the size of the array
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
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.