IndexError: list assignment index out of range in Python

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
9 min

banner

# Table of Contents

  1. IndexError: list assignment index out of range
  2. (CSV) IndexError: list index out of range
  3. sys.argv[1] IndexError: list index out of range
  4. IndexError: pop index out of range

Make sure to click on the correct subheading depending on your error message.

# IndexError: list assignment index out of range in Python

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').

indexerror list assignment index out of range

Here is an example of how the error occurs.

main.py
my_list = ['a', 'b', 'c'] # โ›”๏ธ IndexError: list assignment index out of range my_list[3] = 'd'

assignment to index out of range

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.

abc
012

Trying to assign a value to any positive index outside the range of 0-2 would cause the IndexError.

# Adding an item to the end of the list with append()

If you need to add an item to the end of a list, use the list.append() method instead.

main.py
my_list = ['a', 'b', 'c'] my_list.append('d') my_list.append('e') print(my_list) # ๐Ÿ‘‰๏ธ ['a', 'b', 'c', 'd', 'e']

adding an item to end of list with append

The list.append() method adds an item to the end of the list.

The method returns None as it mutates the original list.

# Changing the value of the element at the last index in the list

If you meant to change the value of the last index in the list, use -1.

main.py
my_list = ['a', 'b', 'c'] my_list[-1] = 'z' print(my_list) # ๐Ÿ‘‰๏ธ ['a', 'b', 'z']

change value of element at last index in list

When the index starts with a minus, we start counting backward from the end of the list.

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(a_list) - 1.

# Declaring a list that contains N elements and updating a certain index

Alternatively, you can declare a list that contains N elements with None values.

main.py
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.

It doesn't have to be 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.

# Using a try/except statement to handle the error

If you need to handle the error if the specified list index doesn't exist, use a try/except statement.

main.py
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.

main.py
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.

# Getting the length of a list

If you need to get the length of the list, use the len() function.

main.py
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.

main.py
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')
If a list has a length of 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.

# Trying to assign a value to an empty list at a specific index

Note that if you try to assign to an empty list at a specific index, you'd always get an IndexError.

main.py
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.

# Use the extend() method to add multiple items to the end of a list

If 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.

main.py
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.

# (CSV) IndexError: list index out of range in Python

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.

csv indexerror list index out of range

Here is an example of how the error occurs.

Assume we have the following CSV file.

employees.csv
first_name,last_name Alice,Smith Bob,Smith Carl,Smith

And we are trying to read it as follows.

main.py
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])
The second line in the CSV file is empty, so the row variable stores an empty list on the second iteration.

# Check if the list contains elements before accessing it

One way to solve the error is to check if the list contains any elements before accessing it at an index.

main.py
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:

  • constants defined to be falsy: None and False.
  • 0 (zero) of any numeric type
  • empty sequences and collections: "" (empty string), () (empty tuple), [] (empty list), {} (empty dictionary), set() (empty set), range(0) (empty range).
Notice that empty lists are falsy and lists that contain at least 1 item are truthy.

# Check if the index you are trying to access exists in the list

Alternatively, you can check whether the specific index you are trying to access exists in the list.

main.py
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).

If a list has a length of 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.

# Use a try/except statement to handle the error

Alternatively, you can use a try/except block to handle the error.

main.py
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.

# sys.argv[1] IndexError: list index out of range in Python

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.

sys argv indexerror list index out of range

Here is an example of how the error occurs.

main.py
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.

Where argv[0] is the name of the script, argv[1] is the first provided command line argument, etc.

# Provide all of the required command line arguments

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.

main.py
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.

# Check if the sys.argv list contains the index

If 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.

main.py
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).

If a list has a length of 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.

# Using a try/except statement to handle the error

Alternatively, you can use a try/except block to handle the error.

main.py
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.

# IndexError: pop index out of range in Python

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.

indexerror pop index out of range

Here is an example of how the error occurs.

main.py
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.

abc
012
If we pass any positive index outside the range 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.

main.py
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.

If no index is specified, the 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().

main.py
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).

If a list has a length of 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().

Note that calling pop() on an empty list also causes an error.

An alternative approach to handle the error is to use a try/except block.

main.py
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.

# 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