Last updated: Apr 8, 2024
Reading timeยท9 min
Make sure to click on the correct subheading depending on your error message.
The Python "IndexError: list assignment index out of range" occurs when we try to assign a value at an index that doesn't exist in the list.
To solve the error, use the append()
method to add an item to the end of the
list, e.g. my_list.append('b')
.
Here is an example of how the error occurs.
my_list = ['a', 'b', 'c'] # โ๏ธ IndexError: list assignment index out of range my_list[3] = 'd'
The list has a length of 3
. Since indexes in Python are zero-based, the first
index in the list is 0
, and the last is 2
.
a | b | c |
---|---|---|
0 | 1 | 2 |
Trying to assign a value to any positive index outside the range of 0-2
would
cause the IndexError
.
If you need to add an item to the end of a list, use the list.append()
method
instead.
my_list = ['a', 'b', 'c'] my_list.append('d') my_list.append('e') print(my_list) # ๐๏ธ ['a', 'b', 'c', 'd', 'e']
The list.append() method adds an item to the end of the list.
The method returns None as it mutates the original list.
If you meant to change the value of the last index in the list, use -1
.
my_list = ['a', 'b', 'c'] my_list[-1] = 'z' print(my_list) # ๐๏ธ ['a', 'b', 'z']
When the index starts with a minus, we start counting backward from the end of the list.
0
, and the last item has an index of -1
or len(a_list) - 1
.Alternatively, you can declare a list that contains N elements with None
values.
my_list = [None] * 5 print(my_list) # ๐๏ธ [None, None, None, None, None] my_list[4] = 'hello' print(my_list) # ๐๏ธ [None, None, None, None, 'hello']
The item you specify in the list will be contained N times in the new list the operation returns.
None
, the value could be 0
, an empty string or any other value that suits your use case.Make sure to wrap the value you want to repeat in a list.
If the list contains a value at the specific index, then you are able to change it.
try/except
statement to handle the errorIf you need to handle the error if the specified list index doesn't exist, use a try/except statement.
my_list = ['a', 'b', 'c'] try: my_list[3] = 'd' except IndexError: # ๐๏ธ this runs print('The specified assignment index does NOT exist')
The list in the example has 3 elements, so its last element has an index of 2
.
We wrapped the assignment in a try/except
block, so the IndexError
is
handled by the except
block.
You can also use a pass
statement in the except
block if you need to ignore
the error.
my_list = ['a', 'b', 'c'] try: my_list[3] = 'd' except IndexError: pass
The pass statement does nothing and is used when a statement is required syntactically but the program requires no action.
If you need to get the length of the list, use the len()
function.
my_list = ['a', ' b', 'c'] print(len(my_list)) # ๐๏ธ 3
The len() function returns the length (the number of items) of an object.
The argument the function takes may be a sequence (a string, tuple, list, range or bytes) or a collection (a dictionary, set, or frozen set).
If you need to
check if an index exists before
assigning a value, use an if
statement.
my_list = ['a', 'b', 'c'] idx = 3 if len(my_list) > idx: my_list[idx] = 'Z' print(my_list) else: # ๐๏ธ This runs print(f'index {idx} is out of range')
3
, then its last index is 2
(because indexes are zero-based).This means that you can check if the list's length is greater than the index you are trying to assign to.
Note that if you try to assign to an empty list at a specific index, you'd
always get an IndexError
.
my_list = [] print(my_list) # ๐๏ธ [] print(len(my_list)) # ๐๏ธ 0 # โ๏ธ IndexError: list assignment index out of range my_list[0] = 'a'
You should print the list you are trying to access and its length to make sure the variable stores what you expect.
extend()
method to add multiple items to the end of a listIf you need to add multiple items to the end of a list, use the extend()
method.
The list.extend method takes an iterable (such as a list) and extends the list by appending all of the items from the iterable.
my_list = ['a', 'b'] my_list.extend(['c', 'd', 'e']) print(my_list) # ๐๏ธ ['a', 'b', 'c', 'd', 'e']
The list.extend
method returns None
as it mutates the original list.
The Python CSV "IndexError: list index out of range" occurs when we try to access a list at an index out of range, e.g. an empty row in a CSV file.
To solve the error, check if the row isn't empty before accessing it at an index, or check if the index exists in the list.
Here is an example of how the error occurs.
Assume we have the following CSV
file.
first_name,last_name Alice,Smith Bob,Smith Carl,Smith
And we are trying to read it as follows.
import csv with open('employees.csv', newline='', encoding='utf-8') as csvfile: csv_reader = csv.reader(csvfile, delimiter=',') for row in csv_reader: # โ๏ธ IndexError: list index out of range print(row[0])
CSV
file is empty, so the row
variable stores an empty list on the second iteration.One way to solve the error is to check if the list contains any elements before accessing it at an index.
import csv with open('employees.csv', newline='', encoding='utf-8') as csvfile: csv_reader = csv.reader(csvfile, delimiter=',') for row in csv_reader: if row: # ๐๏ธ check if row contains items print(row[0])
The if
statement checks if the list is truthy on each iteration.
All values that are not truthy are considered falsy. The falsy values in Python are:
None
and False
.0
(zero) of any numeric type""
(empty string), ()
(empty tuple), []
(empty list), {}
(empty dictionary), set()
(empty set), range(0)
(empty
range).Alternatively, you can check whether the specific index you are trying to access exists in the list.
import csv with open('employees.csv', newline='', encoding='utf-8') as csvfile: csv_reader = csv.reader(csvfile, delimiter=',') idx = 1 for row in csv_reader: if len(row) > idx: print(row[idx])
The len() function returns the length (the number of items) of an object.
The argument the function takes may be a sequence (a string, tuple, list, range or bytes) or a collection (a dictionary, set, or frozen set).
2
, then its last index is 1
(because indexes are zero-based).This means that you can check if the list's length is greater than the index you are trying to access.
try/except
statement to handle the errorAlternatively, you can use a try/except
block to handle the error.
import csv with open('employees.csv', newline='', encoding='utf-8') as csvfile: csv_reader = csv.reader(csvfile, delimiter=',') for row in csv_reader: try: print(row[1]) except IndexError: print('except block ran') continue
We try to access the list of the current iteration at index 1
, and if an
IndexError
is raised, we can handle it in the except
block or continue to
the next iteration.
The sys.argv "IndexError: list index out of range in Python" occurs when we run a Python script without specifying values for the required command line arguments.
To solve the error, provide values for the required arguments, e.g.
python main.py first second
.
Here is an example of how the error occurs.
import sys print(sys.argv) # ๐๏ธ ['main.py'] print(sys.argv[0]) # ๐๏ธ 'main.py' # โ๏ธ IndexError: list index out of range print(sys.argv[1])
I ran the script with python main.py
.
The sys.argv list contains the command line arguments that were passed to the Python script.
argv[0]
is the name of the script, argv[1]
is the first provided command line argument, etc.To solve the error, make sure to provide all of the required command line
arguments when running the script, e.g. python main.py first second
.
import sys print(sys.argv) # ๐๏ธ ['main.py', 'first', 'second'] print(sys.argv[0]) # ๐๏ธ 'main.py' print(sys.argv[1]) # ๐๏ธ 'first' print(sys.argv[2]) # ๐๏ธ 'second'
Notice that the first item in the list is always the name of the script.
It is operating system dependent if this is the full pathname or not.
sys.argv
list contains the indexIf you don't have to always specify all of the command line arguments that your
script tries to access, use an if statement to check if the sys.argv
list
contains the index that you are trying to access.
import sys print(sys.argv) # ๐๏ธ ['main.py'] idx = 1 if len(sys.argv) > idx: print(sys.argv[idx]) else: # ๐๏ธ this runs print(f'index {idx} out of range')
I ran the script as python main.py
without providing any command line
arguments, so the condition wasn't met and the else
block ran.
The len() function returns the length (the number of items) of an object.
The argument the function takes may be a sequence (a string, tuple, list, range or bytes) or a collection (a dictionary, set, or frozen set).
1
, then its last index is 0
(because indexes are zero-based).This means that you can check if the list's length is greater than the index you are trying to access.
try/except
statement to handle the errorAlternatively, you can use a try/except
block to handle the error.
import sys print(sys.argv) # ๐๏ธ ['main.py'] try: print(sys.argv[1]) except IndexError: # ๐๏ธ this runs print('index out of range')
We tried accessing the list item at index 1
which raised an IndexError
exception.
You can handle the error or use the pass
keyword in the except
block.
The Python "IndexError: pop index out of range" occurs when we pass an index
that doesn't exist in the list to the pop()
method.
To solve the error, pass an index that exists to the method or call the pop()
method without arguments to remove the last item from the list.
Here is an example of how the error occurs.
my_list = ['a', 'b', 'c'] # โ๏ธ IndexError: pop index out of range result = my_list.pop(3)
The list has a length of 3
. Since indexes in Python are zero-based, the first
item in the list has an index of 0
, and the last an index of 2
.
a | b | c |
---|---|---|
0 | 1 | 2 |
0-2
to the pop()
method, we would get an IndexError
.If you need to remove the last item in the list, call the method without passing it an index.
my_list = ['a', 'b', 'c'] result = my_list.pop() print(result) # ๐๏ธ 'c' # ๐๏ธ ['a', 'b'] print(my_list)
The list.pop
method removes the item at the given position in the list and
returns it.
pop()
method removes and returns the last item in the list.You can also use negative indices to count backward, e.g. my_list.pop(-1)
removes the last item of the list, and my_list.pop(-2)
removes the
second-to-last item.
Alternatively, you can check if an item at the specified index exists before
passing it to pop()
.
my_list = ['a', 'b', 'c'] print(len(my_list)) # ๐๏ธ 3 idx = 3 if len(my_list) > idx: result = my_list.pop(idx) print(result) else: # ๐๏ธ This runs print(f'index {idx} is out of range')
The len() function returns the length (the number of items) of an object.
The argument the function takes may be a sequence (a string, tuple, list, range or bytes) or a collection (a dictionary, set, or frozen set).
3
, then its last index is 2
(because indexes are zero-based).This means that you can check if the list's length is greater than the index you
are passing to pop()
.
pop()
on an empty list also causes an error.An alternative approach to handle the error is to use a try/except
block.
my_list = ['a', 'b', 'c'] idx = 3 try: result = my_list.pop(idx) except IndexError: # ๐๏ธ This runs print(f'index {idx} is out of range')
If calling the pop()
method with the provided index raises an IndexError
,
the except
block is run, where we can handle the error or use the pass
keyword to ignore it.
You can learn more about the related topics by checking out the following tutorials: