Skip to main content

How to Check for Valid List Index in Python

Accessing elements in a list by their index is a fundamental operation in Python. However, accessing an index that doesn't exist in the list will cause an IndexError exception.

This guide explores how to check if an index is valid and how to get a default value when accessing an index that is out of range, using a variety of methods.

Checking if an Index Exists

To check if a given index exists in a list, compare it to the list's length.

Checking for Valid Index using Length

You can verify that the index is within the list's bounds using a comparison to the list length. If the index is a positive value, make sure it is less than the length of the list:

my_list = ['tutorial', 'reference', 'com']
index = 2
if index < len(my_list):
print('The index exists in the list', my_list[index]) # Output: The index exists in the list com
else:
print('The index does NOT exist in the list')
  • The check index < len(my_list) verifies that the index is valid.
  • Note that the indexes in the list are 0 based, which means the last item in a list has index of len(my_list) - 1.

You can check if a specific index is valid, using comparison operator with the list length:

my_list = ['tutorial', 'reference', 'com']

print(2 < len(my_list)) # Output: True
print(3 < len(my_list)) # Output: False

Handling Negative Indices

To handle both positive and negative indices, use this more specific condition:

my_list = ['tutorial', 'reference', 'com']
index = -30

if -len(my_list) <= index < len(my_list):
print('The index exists in the list', my_list[index])
else:
print('The index does NOT exist in the list') # Output: The index does NOT exist in the list
  • The code checks if -len(my_list) <= index < len(my_list) in order to make sure negative indexes are also taken into consideration.
  • The largest valid negative index in a list is equal to -len(my_list).

Checking if an Index Exists using try/except

Another approach for checking if an index exists is to attempt access and handle the potential IndexError using try and except block.

my_list = ['tutorial', 'reference', 'com']
try:
index = 100
print(my_list[index])
print(f'index {index} exists in the list') # This won't run if there's an exception
except IndexError:
print('The specified index does NOT exist') # Output: The specified index does NOT exist
  • The try block attempts to access the list item at the specified index, which will throw an IndexError exception if the index is not within the list's bounds.
  • The except IndexError block will be executed only when the exception is raised.

Getting a Default Value on Index Out of Range

To avoid exceptions when an index is out of range, you can define a helper function that returns a default value in such cases.

Using a try/except block

This can be achieved using try/except.

def get_item(li, index, default=None):
try:
return li[index]
except IndexError:
return default

my_list = ['tutorial', 'reference', 'com']

print(get_item(my_list, 1)) # Output: reference
print(get_item(my_list, 25)) # Output: None
print(get_item(my_list, 25, 'default value')) # Output: default value
print(get_item(my_list, -1)) # Output: com
print(get_item(my_list, -25)) # Output: None
print(get_item(my_list, -25, 'default value')) # Output: default value
  • The function will try to get a value by index, and if an exception is raised it will return the default value instead.
  • This approach also handles negative values, providing a way to get a default value when those are out of range.

Using Length Check

You can also perform a length check to determine if the index is valid before attempting to access an item in the list:

def get_item(li, index, default=None):
return li[index] if -len(li) <= index < len(li) else default

my_list = ['tutorial', 'reference', 'com']

print(get_item(my_list, 1)) # Output: reference
print(get_item(my_list, 25, 'default value')) # Output: default value
print(get_item(my_list, -1)) # Output: com
print(get_item(my_list, -25, 'default value')) # Output: default value
  • The if -len(li) <= index < len(li) check verifies that the specified index is within the list's bounds before accessing the item.