TryBugHunt

IndexError: list assignment index out of range

IndexError: list assignment index out of range in Python means you tried to put a value at a position the list does not have yet. Assigning to items[i] only replaces an existing item; it never makes the list longer.

PythonPattern: Off-by-one errors

How do I fix IndexError: list assignment index out of range?

IndexError: list assignment index out of range means you assigned to items[i] at a position the list does not have yet. Assigning by index only replaces existing items; it never grows a Python list. To add a value at the end, use items.append(x). To fill by position, create the list first with [None] * size.

  1. 1. Print length and indexAdd print(len(items), i) before the failing line. The index must be below the length.
  2. 2. Use append() to addIf the list starts empty, items[i] = x fails even for 0. Write items.append(x) instead.
  3. 3. Pre-size the listIf positions matter, create it first: seats = [None] * 10, then assign seats[3] = "Ada".

What does IndexError: list assignment index out of range mean?

In some languages, writing to position 5 of an empty array grows it. Python lists do not work that way. items[0] = x only works if the list already has a position 0. To add a new item at the end, use items.append(x). To fill a list by position, create it at the right size first.

Why does IndexError: list assignment index out of range happen?

1. Assigning into an empty list

An empty list has no positions at all, so even index 0 does not exist.

Breaks

squares = []
for i in range(5):
    squares[i] = i * i

Works

squares = []
for i in range(5):
    squares.append(i * i)

2. Copying a list item by item into a new list

The new list starts empty, so copy[i] does not exist yet.

Breaks

copy = []
for i in range(len(nums)):
    copy[i] = nums[i]

Works

copy = nums.copy()   # or: copy = [n for n in nums]

3. Filling positions in any order

If you must set items by position, create the list with the right length first.

Breaks

seats = []
seats[3] = "Ada"

Works

seats = [None] * 10
seats[3] = "Ada"

How to find it in your own code

Checklist: 1) print(len(items), i) just before the failing line. 2) If the list is shorter than i + 1, you are adding, not replacing: use append(). 3) If positions matter, create the list first with [None] * size or [0] * size. 4) If you meant to change a value, check the index is between 0 and len(items) - 1.

Practise off-by-one errors

None of the challenges raises this exact error yet. These practise the same kind of bug.

Still not sure why yours breaks?

Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.

Related error guides

View all off-by-one errors →