IndexError: list assignment index out of range in Python | bobbyhadz (2023)

# 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 tryto 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 thelist, e.g. my_list.append('b').

IndexError: list assignment index out of range in Python | bobbyhadz (1)

Here is an example of how the error occurs.

main.py

Copied!

my_list = ['a', 'b', 'c']# ⛔️ IndexError: list assignment index out of rangemy_list[3] = 'd'

IndexError: list assignment index out of range in Python | bobbyhadz (2)

The list has a length of 3. Since indexes in Python are zero-based, the firstindex 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 wouldcause 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() methodinstead.

main.py

Copied!

my_list = ['a', 'b', 'c']my_list.append('d')my_list.append('e')print(my_list) # 👉️ ['a', 'b', 'c', 'd', 'e']

IndexError: list assignment index out of range in Python | bobbyhadz (3)

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

The method returns None as it mutates the originallist.

# 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

Copied!

my_list = ['a', 'b', 'c']my_list[-1] = 'z'print(my_list) # 👉️ ['a', 'b', 'z']

IndexError: list assignment index out of range in Python | bobbyhadz (4)

When the index starts with a minus, we start counting backward from the end ofthe 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 Nonevalues.

main.py

Copied!

my_list = [None] * 5print(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 theoperation 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 changeit.

# 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 atry/except statement.

main.py

Copied!

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 ishandled by the except block.

You can also use a pass statement in the except block if you need to ignorethe error.

main.py

Copied!

my_list = ['a', 'b', 'c']try: my_list[3] = 'd'except IndexError: pass

The pass statement does nothing and is usedwhen 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

Copied!

my_list = ['a', ' b', 'c']print(len(my_list)) # 👉️ 3

The len() function returnsthe length (the number of items) of an object.

The argument the function takes may be a sequence (a string, tuple, list, rangeor bytes) or a collection (a dictionary, set, or frozen set).

If you need tocheck if an index exists beforeassigning a value, use an if statement.

main.py

Copied!

my_list = ['a', 'b', 'c']idx = 3if 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 youare 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'dalways get an IndexError.

main.py

Copied!

my_list = []print(my_list) # 👉️ []print(len(my_list)) # 👉️ 0# ⛔️ IndexError: list assignment index out of rangemy_list[0] = 'a'

You should print the list you are trying to access and its length to make surethe 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.extendmethod takes an iterable (such as a list) and extends the list by appending allof the items from the iterable.

main.py

Copied!

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 toaccess 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 anindex, or check if the index exists in the list.

IndexError: list assignment index out of range in Python | bobbyhadz (5)

Here is an example of how the error occurs.

Assume we have the following CSV file.

employees.csv

Copied!

first_name,last_nameAlice,SmithBob,SmithCarl,Smith

And we are trying to read it as follows.

main.py

Copied!

import csvwith 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 beforeaccessing it at an index.

main.py

Copied!

import csvwith 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 Pythonare:

  • 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) (emptyrange).

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 accessexists in the list.

main.py

Copied!

import csvwith 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 returnsthe length (the number of items) of an object.

The argument the function takes may be a sequence (a string, tuple, list, rangeor 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 youare 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

Copied!

import csvwith 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 anIndexError is raised, we can handle it in the except block or continue tothe 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 runa Python script without specifying values for the required command linearguments.

To solve the error, provide values for the required arguments, e.g.python main.py first second.

IndexError: list assignment index out of range in Python | bobbyhadz (6)

Here is an example of how the error occurs.

main.py

Copied!

import sysprint(sys.argv) # 👉️ ['main.py']print(sys.argv[0]) # 👉️ 'main.py'# ⛔️ IndexError: list index out of rangeprint(sys.argv[1])

I ran the script with python main.py.

The sys.argv listcontains 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 linearguments when running the script, e.g. python main.py first second.

main.py

Copied!

import sysprint(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 yourscript tries to access, use an if statement to check if the sys.argv listcontains the index that you are trying to access.

main.py

Copied!

import sysprint(sys.argv) # 👉️ ['main.py']idx = 1if 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 linearguments, so the condition wasn't met and the else block ran.

The len() function returnsthe length (the number of items) of an object.

The argument the function takes may be a sequence (a string, tuple, list, rangeor 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 youare 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

Copied!

import sysprint(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 IndexErrorexception.

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 indexthat 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: list assignment index out of range in Python | bobbyhadz (7)

Here is an example of how the error occurs.

main.py

Copied!

my_list = ['a', 'b', 'c']# ⛔️ IndexError: pop index out of rangeresult = my_list.pop(3)

The list has a length of 3. Since indexes in Python are zero-based, the firstitem 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 passingit an index.

main.py

Copied!

my_list = ['a', 'b', 'c']result = my_list.pop()print(result) # 👉️ 'c'# 👇️ ['a', 'b']print(my_list)

The list.pop method removes theitem 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 thesecond-to-last item.

Alternatively, you can check if an item at the specified index exists beforepassing it to pop().

main.py

Copied!

my_list = ['a', 'b', 'c']print(len(my_list)) # 👉️ 3idx = 3if 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 returnsthe length (the number of items) of an object.

The argument the function takes may be a sequence (a string, tuple, list, rangeor 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 youare 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

Copied!

my_list = ['a', 'b', 'c']idx = 3try: 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 passkeyword to ignore it.

# Additional Resources

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

  • IndexError: index 0 is out of bounds for axis 0 with size 0
  • IndexError: invalid index to scalar variable in Python
  • IndexError: pop from empty list in Python [Solved]
  • Replacement index 1 out of range for positional args tuple
  • IndexError: string index out of range in Python [Solved]
  • IndexError: too many indices for array in Python [Solved]
  • IndexError: tuple index out of range in Python [Solved]
Top Articles
Latest Posts
Article information

Author: Ray Christiansen

Last Updated: 27/08/2023

Views: 6323

Rating: 4.9 / 5 (69 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Ray Christiansen

Birthday: 1998-05-04

Address: Apt. 814 34339 Sauer Islands, Hirtheville, GA 02446-8771

Phone: +337636892828

Job: Lead Hospitality Designer

Hobby: Urban exploration, Tai chi, Lockpicking, Fashion, Gunsmithing, Pottery, Geocaching

Introduction: My name is Ray Christiansen, I am a fair, good, cute, gentle, vast, glamorous, excited person who loves writing and wants to share my knowledge and understanding with you.