Python | Handling no element found in index()

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 : 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.



filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output :

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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.