Check if an index exists in a List in Python

avatar
Borislav Hadzhiev

Last updated: Apr 10, 2024
5 min

banner

# Table of Contents

  1. Check if an index exists in a List in Python
  2. Get a default value on index out of range in Python

# Check if an index exists in a List in Python

To check if an index exists in a list:

  1. Check if the index is less than the list's length.
  2. If the condition is met, the index exists in the list.
  3. If the index is equal to or greater than the list's length, it doesn't exist.
main.py
my_list = ['bobby', 'hadz', 'com'] index = 2 if index < len(my_list): # ๐Ÿ‘‡๏ธ this runs print('The index exists in the list', my_list[index]) else: print('The index does NOT exist in the list') print(2 < len(my_list)) # ๐Ÿ‘‰๏ธ True print(3 < len(my_list)) # ๐Ÿ‘‰๏ธ False

check if index exists in list

The code for this article is available on GitHub

If the specified index is less than the list's length, then it exists.

If the list has a length of 3, then there are 3 elements in the list.

If there are 3 elements in the list, the last element has an index of 2.

Python indexes are zero-based, so the first item in a list has an index of 0, and the last item has an index of -1 or len(my_list) - 1.

Since indexes are zero-based, the last item in a list will always have an index of len(my_list) - 1.

If the index is less than the list's length, it's safe to access the list at the specified index.

# Handling the case where the index might be negative

Here is an example that handles the scenario where the index might be negative.

main.py
my_list = ['bobby', 'hadz', 'com'] index = -30 if -len(my_list) <= index < len(my_list): print('The index exists in the list', my_list[index]) else: # ๐Ÿ‘‡๏ธ this runs print('The index does NOT exist in the list')

handling the case where the index might be negative

The code for this article is available on GitHub

The if statement checks if the length of the list is greater than the specified index.

We also check if the negated length of the list is less than or equal to the index.

This is necessary to handle negative indices, e.g. -30.

If the list has a length of 3, the largest negative index in the list is -3.

In other words, the largest negative index in a list is equal to -len(my_list).

Negative indices can be used to count backward, e.g. my_list[-1] returns the last item in the list and my_list[-2] returns the second to last item.

main.py
my_list = ['bobby', 'hadz', 'com'] print(my_list[-1]) # ๐Ÿ‘‰๏ธ com print(my_list[-2]) # ๐Ÿ‘‰๏ธ hadz print(my_list[-3]) # ๐Ÿ‘‰๏ธ bobby

# Check if an index exists in a List using try/except

You can also use a try/except statement to check if an index exists in a list.

main.py
my_list = ['bobby', 'hadz', 'com'] try: index = 100 print(my_list[index]) print(f'index {index} exists in the list') except IndexError: # ๐Ÿ‘‡๏ธ this runs print('The specified index does NOT exist')

check if index exists in list using try except

The code for this article is available on GitHub

We try to access index 100 in the try block and if the index doesn't exist, an IndexError exception is raised and is then handled by the except block.

If the try block completes successfully, the index exists in the list.

If the except block runs, the index doesn't exist in the list.

You don't have to worry about handling negative indices when you use this approach because it does that automatically.

# Get a default value on index out of range in Python

To get a default value on index out of range exception:

  1. Access the list at the specified index in a try/except block.
  2. If the list index out of range exception is raised, return a default value.
  3. Otherwise, return the list item at the specified index.
main.py
def get_item(li, index, default=None): try: return li[index] except IndexError: return default my_list = ['bobby', 'hadz', 'com'] print(get_item(my_list, 1)) # ๐Ÿ‘‰๏ธ hadz print(get_item(my_list, 25)) # ๐Ÿ‘‰๏ธ None print(get_item(my_list, 25, 'default value')) # ๐Ÿ‘‰๏ธ default value print(get_item(my_list, -1)) # ๐Ÿ‘‰๏ธ com print(get_item(my_list, -25)) # ๐Ÿ‘‰๏ธ None print(get_item(my_list, -25, 'default value')) # ๐Ÿ‘‰๏ธ default value
The code for this article is available on GitHub

We used a try/except block to return a default value on a 'list index out of range' exception.

We access the list at the specified index in the try block and if the index is out of range, an IndexError is raised.

main.py
my_list = ['bobby', 'hadz', 'com'] # โ›”๏ธ IndexError: list index out of range print(my_list[25])

We handle the IndexError in the except block by returning a default value.

The default value is set to None unless the user provides a third argument in the call to the function.
main.py
def get_item(li, index, default=None): try: return li[index] except IndexError: return default my_list = ['bobby', 'hadz', 'com'] print(get_item(my_list, 25)) # ๐Ÿ‘‰๏ธ None print(get_item(my_list, 25, 'default value')) # ๐Ÿ‘‰๏ธ default value

The function returns the list item at the specified index if it is in range, otherwise, a default value is returned.

This approach also handles negative indexes.

main.py
def get_item(li, index, default=None): try: return li[index] except IndexError: return default my_list = ['bobby', 'hadz', 'com'] print(get_item(my_list, -1)) # ๐Ÿ‘‰๏ธ com print(get_item(my_list, -25)) # ๐Ÿ‘‰๏ธ None print(get_item(my_list, -25, 'default value')) # ๐Ÿ‘‰๏ธ default value
Negative indices can be used to count backward, e.g. my_list[-1] returns the last item in the list and my_list[-2] returns the second to last item.

Alternatively, you can check the list's length.

# Get a default value on index out of range using len()

This is a three-step process:

  1. Check if the provided index is in range.
  2. If the index is in range, access the list item at the specified index.
  3. Otherwise, return a default value.
main.py
def get_item(li, index, default=None): return li[index] if -len(li) <= index < len(li) else default my_list = ['bobby', 'hadz', 'com'] print(get_item(my_list, 1)) # ๐Ÿ‘‰๏ธ hadz print(get_item(my_list, 25)) # ๐Ÿ‘‰๏ธ None print(get_item(my_list, 25, 'default value')) # ๐Ÿ‘‰๏ธ default value print(get_item(my_list, -1)) # ๐Ÿ‘‰๏ธ com print(get_item(my_list, -25)) # ๐Ÿ‘‰๏ธ None print(get_item(my_list, -25, 'default value')) # ๐Ÿ‘‰๏ธ default value
The code for this article is available on GitHub

We used an inline if/else statement to check if the specified index is in range.

The if statement first checks if the negated length of the list is less than or equal to the index.

This is necessary to handle negative indexes, e.g. my_list[-25].

If the list has a length of 3, the largest negative index in the list is -3.

In other words, the largest negative index in a list is equal to -len(my_list).

The if statement also checks if the index is less than the list's length.

Python indexes are zero-based, so the first item in a list has an index of 0, and the last item has an index of -1 or len(my_list) - 1.

Indexes are zero-based, so the last item in the list will always have an index of len(my_list) - 1.

If the two conditions are met, we access the list item at the specified index.

main.py
def get_item(li, index, default=None): return li[index] if -len(li) <= index < len(li) else default my_list = ['bobby', 'hadz', 'com'] print(get_item(my_list, 1)) # ๐Ÿ‘‰๏ธ hadz print(get_item(my_list, 25, 'default value')) # ๐Ÿ‘‰๏ธ default value print(get_item(my_list, -1)) # ๐Ÿ‘‰๏ธ com print(get_item(my_list, -25, 'default value')) # ๐Ÿ‘‰๏ธ default value

Otherwise, we return a default value.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev