Knowee
Questions
Features
Study Tools

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

🧐 Not the exact question you are looking for?Go ask a question

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.

This problem has been solved

Similar Questions

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.

Fill in the blank: In Python, the index() method interprets a string as a _____.1 pointstring slicebooleansubstringsequence of characters

How do you find the index of the first occurrence of an element in an array?Optionsfind(element)index(element)locate(element)search(element)

What will be printed by the following code?for i in range(5):    for j in range(5, 0, -1):        if i == j:            print(i, end=" ")

1/2

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.