Open In App

Python | Handling no element found in index()

Last Updated : 16 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python lists, we are confronted with a problem in which we need to check whether an element is present in a list and also where exactly, which index it occurs. The convenient solution of it is to use index(). But problem with this can come that sometimes, the desired element might not be present in the list. Let’s discuss a method in which this exception can be handled. 

Method #1: Using ValueError + try + except In this method, knowing that the value might not exists, we catch the error in try-except block. The ValueError is raised in the absence and can be used to catch this particular exception. 

Python3




# Python3 code to demonstrate working of
# Handling no element found in index()
# Using try + except + ValueError
 
# initializing list
test_list = [6, 4, 8, 9, 10]
 
# printing list
print("The original list : " + str(test_list))
 
# Handling no element found in index()
# Using try + except + ValueError
try :
    test_list.index(11)
    res = "Element found"
except ValueError :
    res = "Element not in list !"
 
# Printing result
print("The value after catching error : " + str(res))


Output : 

 
The original list : [6, 4, 8, 9, 10]
The value after catching error : Element not in list!

Time Complexity: O(n), where n is the length of the list test_list 
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list 

Method #2: Using conditions

In the above code, we first define a list of values (original_list) and a value to search for in the list (value_to_find). We then use the in operator to check if value_to_find is in original_list. If the value is in the list, we get its index using the index() method and store it in the variable index. We then print the index of the value to the console using a formatted string. If the value is not in the list, the else block is executed and the message “Element not in list!” is printed to the console.

Python3




# Define a list of values to search for an element in
original_list = [6, 4, 8, 9, 10]
 
# Define the value to search for in the list
value_to_find = 7
 
# Check if the value is in the list using the 'in' operator
if value_to_find in original_list:
    # If the value is in the list, get its index using the 'index()' method
    index = original_list.index(value_to_find)
    # Print the index of the value to the console
    print(f"The index of {value_to_find} is {index}")
else:
    # If the value is not in the list, print a message to the console
    print("Element not in list!")


Output

Element not in list!

Time complexity: O(n)
Auxiliary Space: O(1)

Method #3: Using enumerate() function and a loop:

Step-by-step approach:

  • Initialize the input list test_list with some values
  • Initialize the key variable key with the value to search for
  • Use a for loop with enumerate() to iterate over each element and index of test_list
  • Check if the current element matches the key using an if statement
  • If the element matches, print the index where it was found using the print() function and the formatted string f”Element found at index {i}”
  • Break out of the loop using the break statement to stop searching for the element once it is found
  • If the loop completes without finding the element, print a message indicating that the element was not found 8.using the print() function and the string “Element not in list!”

Python3




test_list = [6, 4, 8, 9, 10]
# printing list
print("The original list : " + str(test_list))
key = 11
for i, elem in enumerate(test_list):
    if elem == key:
        print(f"Element found at index {i}")
        break
else:
    print("Element not in list!")
#This code is contributed by jyothi pinjala


Output

The original list : [6, 4, 8, 9, 10]
Element not in list!

Time complexity: O(n), as it iterates over the list once, where n is the length of the list. 
Auxiliary space: O(1), as it uses a constant amount of extra space to store the loop variables.

Method #4: Using find() method

In this method we checks if the key is present in the list using the in operator. If the key is present, it uses the index() method to find the index of the key in the list. If the key is not present, it prints a message indicating that the element is not in the list.

Python3




# initializing list
test_list = [6, 4, 8, 9, 10]
# printing list
print("The original list : " + str(test_list))
key = 11
 
if key in test_list:
    index = test_list.index(key)
    print(f"Element found at index {index}")
else:
    print("Element not in list!")


Output:

The original list : [6, 4, 8, 9, 10]
Element not in list!

Time complexity: O(n), where n is the length of the list.
Auxiliary space: O(1) as it uses a constant amount of extra space 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads