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.
# 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)) |
The original list : [6, 4, 8, 9, 10] The value after catching error : Element not in list!
Recommended Posts:
- Python | Get the Index of first element greater than K
- Python | Multiply each element in a sublist by its index
- Python | Print list after removing element at given index
- Python | Replace elements in second list with index of same element in first list
- Python | Set 5 (Exception Handling)
- File Handling in Python
- Precision Handling in Python
- Multiple Exception Handling in Python
- Python | Handling recursion limit
- Python | 404 Error handling in Flask
- SQL using Python | Set 3 (Handling large data)
- Handling missing keys in Python dictionaries
- ML | Handling Imbalanced Data with SMOTE and Near Miss Algorithm in Python
- Python | Index of Non-Zero elements in Python list
- Python | Slicing list from Kth element to last element
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.



