To check if a list index exists in a list using Python, the easiest way is to use the Python len() function.

def indexExists(list,index):
    if 0 <= index < len(list):
        return True
    else:
        return False

print(indexExists([0,1,2,3,4,5],3))
print(indexExists(["This","is","a","list"],10))

#Output:
True
False

You can also check if an index exists using exception handling.

def indexExists(list,index):
    try:
        list[index]
        return True
    except IndexError:
        return False

print(indexExists([0,1,2,3,4,5],3))
print(indexExists(["This","is","a","list"],10))

#Output:
True
False

When working with collections, the worst feeling to experience is when we get an IndexError exception because we tried to access an element that doesn't exist.

In Python, we can easily check if a list has an index so we won't have to experience getting an IndexError.

To check if a certain list index exists, we check to see if the list index is between 0 and the length of the list.

Below is an example of a Python function which will return True or False depending on if the list index you want exists.

def indexExists(list,index):
    if 0 <= index < len(list):
        return True
    else:
        return False

print(indexExists([0,1,2,3,4,5],3))
print(indexExists(["This","is","a","list"],10))

#Output:
True
False

Checking if List Index Exists Using Exception Handling in Python

You can also check if an index exists using exception handling. When we try to access an element of a list with an index that is out of bounds, we will generate an IndexError.

Therefore, to check if a list index exists or not, we can see if our code raises an error when we try to access an element at a certain index.

Below is a Python function which uses exception handling to see if an index exists in a list.

def indexExists(list,index):
    try:
        list[index]
        return True
    except IndexError:
        return False

print(indexExists([0,1,2,3,4,5],3))
print(indexExists(["This","is","a","list"],10))

#Output:
True
False

Hopefully this article has been useful for you to understand how to check if a list index exists in Python.

Categorized in:

Python,

Last Update: March 20, 2024