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.
The original list : [6, 4, 8, 9, 10] The value after catching error : Element not in list!
- Python | Get the Index of first element greater than K
- Python | Multiply each element in a sublist by its index
- Python - Index match element Product
- Python | Print list after removing element at given index
- Python - Find the index of Minimum element in list
- Python | Replace elements in second list with index of same element in first list
- Precision Handling in Python
- File Handling in Python
- Python | Set 5 (Exception Handling)
- Python | Handling recursion limit
- SQL using Python | Set 3 (Handling large data)
- Python | 404 Error handling in Flask
- Multiple Exception Handling in Python
- Handling missing keys in Python dictionaries
- ML | Handling Imbalanced Data with SMOTE and Near Miss Algorithm in Python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.