Check if Index Exists in Python List

Check if Index Exists in Python List

Fumbani Banda Dec-25, 2021 Oct-19, 2021 Python Python List
  1. Check if Index Exists in Python List Using the List Range
  2. Check if Index Exists in Python List Using The IndexError

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
Fumbani Banda avatar Fumbani Banda avatar

Fumbani is a tech enthusiast. He enjoys writing on Linux and Python as well as contributing to open-source projects.

LinkedIn GitHub

Related Article - Python List

  • Convert a Dictionary to a List in Python
  • Remove All the Occurrences of an Element From a List in Python
  • Remove Duplicates From List in Python
  • Get the Average of a List in Python
  • What Is the Difference Between List Methods Append and Extend
  • Convert a List to String in Python