Last updated: Apr 10, 2024
Reading timeยท5 min
To check if an index exists in a list:
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
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
.
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.
Here is an example that handles the scenario where the index might be negative.
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')
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
.
-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.
my_list = ['bobby', 'hadz', 'com'] print(my_list[-1]) # ๐๏ธ com print(my_list[-2]) # ๐๏ธ hadz print(my_list[-3]) # ๐๏ธ bobby
You can also use a try/except statement to check if an index exists in a list.
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')
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.
To get a default value on index out of range exception:
try/except
block.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
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.
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.
None
unless the user provides a third argument in the call to the function.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.
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
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.
This is a three-step process:
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
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
.
-len(my_list)
.The if
statement also checks if the index is less than the list's length.
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.
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.
You can learn more about the related topics by checking out the following tutorials: