Python - How To Check if Index Exists in Python List

ID : 262

viewed : 119

Tags : PythonPython List

vote vote

97

We will introduce two methods to check if a list index exists using the list range and the IndexError exception.

Check if Index Exists in Python List Using the List Range

We will have to check if the index exists in the range of 0 and the length of the list.

fruit_list = ['Apple','Banana','Pineapple']  for index in range(0,5):     if 0 <= index < len(fruit_list):         print("Index ",index ," in range")     else:         print("Index ",index," not in range") 

Output:

Index  0  in range Index  1  in range Index  2  in range Index  3  not in range Index  4  not in range 

Check if Index Exists in Python List Using The IndexError

When we try to access an index that does not exist in a list, it will raise an IndexError exception.

fruit_list = ['Apple','Banana','Pineapple']  for index in range(0,5):     try:         fruit_list[index]         print("Index ",index," in range")     except IndexError:         print("Index ",index," does not exist") 
Index  0  in range Index  1  in range Index  2  in range Index  3  does not exist Index  4  does not exist 

  • Related HOW TO?