IndexError: list index out of range - 11 Causes and Fixes in Python

IndexError: list index out of range means you asked a list for a position it does not have. Python checks every index against the current length of the sequence, and when the index is equal to or greater than that length (or more negative than -len), it refuses rather than reading whatever memory sits next door.

The traceback points at the line that did the indexing, which is almost never the line that caused the problem. The list got shorter than you assumed, or it was empty all along, or your loop bound was computed once and the data moved underneath it.

This page gives you the one-line fix first, then 11 distinct causes with runnable reproductions, a diagnostic checklist for cases that match none of them, and the design reason this error exists so you recognise the whole family next time. Laptop displaying code with reflection, perfect for tech and programming themes.

ErrorIndexError: list index out of range
Where it happensPython 3.x (and 2.7) - CPython, PyPy, any framework. Raised at runtime at the exact moment a sequence is indexed: scripts, Django/Flask handlers, Celery tasks, notebooks, test code.
What it meansYou asked for position N of a list that holds fewer than N+1 items - usually because the list is empty or shorter than your loop bound assumed.

The Fast Fix

Most of the time you are indexing a list that is shorter than you think, inside a loop that should not be indexing at all. Let Python produce the indices:

# before - range(len(items) + 1) walks one past the end
for i in range(len(items) + 1):
    print(items[i])

# after - no index arithmetic to get wrong
for item in items:
    print(item)

# after, when you genuinely need the position
for i, item in enumerate(items):
    print(i, item)

For a single lookup, guard it instead of hoping:

first = items[0] if items else None

If neither applies, print len(items) and the index on the failing line before it runs - that one log line tells you which of the causes below you have.

What Is Actually Causing It

1. Loop bound runs one index past the end

Reproduce it

items = ["a", "b", "c"]
for i in range(len(items) + 1):   # yields 0, 1, 2, 3
    print(items[i])               # items[3] -> IndexError

Why it happens — range(len(items)) already stops at len(items) - 1, which is the last valid index. Adding + 1, or writing while i <= len(items), makes the final iteration read position len(items) - the first position that does not exist.

The fix

items = ["a", "b", "c"]
for item in items:               # iterate the list, not a number range
    print(item)

for i, item in enumerate(items):  # when the position matters
    print(i, item)

What changed: the + 1 is gone and Python derives the index space from the list itself.

Confirm it worked — Print list(range(len(items))) - the last value must be len(items) - 1. With the fix the loop body runs exactly len(items) times.


2. The list is empty because a filter or query matched nothing

Reproduce it

def first_admin(users):
    return [u for u in users if u["role"] == "admin"][0]

first_admin([{"name": "ada", "role": "dev"}])   # IndexError

Why it happens — The comprehension produced [], and [][0] has no element 0. The failure surfaces at the subscript, far from the place where the data turned out to be missing - a database query, an API response, a filtered config.

The fix

def first_admin(users):
    admins = [u for u in users if u["role"] == "admin"]
    if not admins:
        return None           # or raise a domain-specific error
    return admins[0]

# one-liner equivalent
def first_admin(users):
    return next((u for u in users if u["role"] == "admin"), None)

What changed: the empty case is named and handled instead of being indexed.

Confirm it worked — Call the function with input that matches nothing. You should get None (or your domain error) instead of a traceback.


3. split() returned fewer fields than the format promised

Reproduce it

with open("access.log") as fh:
    for line in fh:
        parts = line.split(",")
        print(parts[3])     # a blank or truncated line -> IndexError

Why it happens — A blank line splits to [""], length 1. A truncated or differently-quoted row yields fewer fields than the happy-path row you tested with, so positional access past that count fails.

The fix

with open("access.log") as fh:
    for lineno, raw in enumerate(fh, start=1):
        line = raw.strip()
        if not line:
            continue
        parts = line.split(",")
        if len(parts) < 4:
            print(f"line {lineno} malformed: {line!r}")
            continue
        print(parts[3])

What changed: blank lines are skipped and short rows are reported with their line number instead of crashing. For real CSV, use the csv module so quoting and embedded commas are handled.

Confirm it worked — Rerun on the same file: every bad row is logged with its line number, and the run completes. grep -c ',' access.log against the line count also exposes ragged rows.


4. Removing items while iterating by index

Reproduce it

nums = [1, 2, 3, 4]
for i in range(len(nums)):
    if nums[i] % 2 == 0:
        nums.remove(nums[i])   # list shrinks under the loop

Why it happens — range(len(nums)) is evaluated once, against the original length of 4. Every remove shortens the list, so the later indices address positions that no longer exist.

The fix

nums = [1, 2, 3, 4]
nums[:] = [n for n in nums if n % 2 != 0]   # same object, rebuilt contents
# or, if rebinding is fine:
# nums = [n for n in nums if n % 2 != 0]

What changed: nothing is mutated mid-traversal; the filtered result replaces the contents in one step. If you must delete in place, iterate reversed(range(len(nums))) so removals only affect indices you have already passed.

Confirm it worked — Log len(nums) at the top of each iteration. In the broken version it changes while the loop runs; after the fix the traversal sees one stable length.


5. Negative index on an empty or shorter-than-expected list

Reproduce it

def last_message(messages):
    return messages[-1]

last_message([])    # IndexError

Why it happens — Negative indices count from the end but are still bounds-checked: -1 needs at least one element, -2 needs two. An empty list has no valid index at all, positive or negative.

The fix

def last_message(messages):
    if not messages:
        return None
    return messages[-1]

# slice alternative - slices clamp instead of raising
tail = messages[-1:]    # [] when empty, [last] otherwise

What changed: the empty list returns a value instead of raising, either via an explicit guard or via a slice.

Confirm it worked — Call it with [] and with a one-element list. Both must return without a traceback.


6. Parallel lists of different lengths share one index

Reproduce it

names = ["ada", "linus", "guido"]
scores = [10, 20]
for i in range(len(names)):
    print(names[i], scores[i])   # i == 2 -> IndexError on scores

Why it happens — A single index assumes the two lists stay the same length. Once one of them is built from a different source - a filtered query, a partially failed batch - the longer list drives the loop off the end of the shorter one.

The fix

names = ["ada", "linus", "guido"]
scores = [10, 20]
for name, score in zip(names, scores, strict=True):   # strict= needs Python 3.10+
    print(name, score)

What changed: zip pairs the lists so no index exists to overflow. Plain zip stops silently at the shorter list; strict=True (Python 3.10 and newer) raises ValueError so the length mismatch is reported at the pairing site. On older versions, assert the lengths first: assert len(names) == len(scores).

Confirm it worked — Run with deliberately mismatched lists. On 3.10+ you get a ValueError naming the mismatch; with the assert you get an AssertionError - either way the failure now points at the data, not at a subscript.


More causes (5 remaining)

7. Counter advanced in the inner loop, used on the outer list

Reproduce it

lines = ["a b", "c"]
i = 0
for line in lines:
    for word in line.split():
        print(lines[i])
        i += 1              # increments per word, not per line

Why it happens — The counter is incremented once per inner item (3 words) but indexes the outer list (2 lines). Manual counters in nested loops drift whenever the inner iteration count differs from the outer one - the classic python indexerror loop bug.

The fix

lines = ["a b", "c"]
for i, line in enumerate(lines):     # index owned by the outer loop
    for word in line.split():
        print(i, line, word)

What changed: the hand-rolled counter is gone; enumerate ties i to the list it indexes.

Confirm it worked — Print i, len(lines) wherever i changes. i must stay below len(lines) for the whole run, and it must not advance inside the inner loop.


8. 2D list indexed with rows and columns swapped

Reproduce it

grid = [
    [1, 2, 3],
    [4, 5, 6],
]                       # 2 rows, 3 columns
for row in range(3):
    for col in range(2):
        print(grid[row][col])   # grid[2] -> IndexError

Why it happens — The outer subscript addresses rows, so its bound is len(grid) (2). The inner subscript addresses columns within one row, bound len(grid[row]) (3). Swapping those two numbers overruns the outer list. Ragged rows break hardcoded column bounds the same way.

The fix

for row in range(len(grid)):
    for col in range(len(grid[row])):   # per-row length survives ragged data
        print(grid[row][col])

# or drop the indices entirely
for row in grid:
    for value in row:
        print(value)

What changed: each bound is read from the structure it indexes, per row.

Confirm it worked — Print len(grid), [len(r) for r in grid] - here 2 [3, 3]. If the inner lengths differ, any hardcoded column bound is wrong.


9. pop() in a loop that never checks for empty

Reproduce it

queue = [1, 2, 3]
while True:
    job = queue.pop(0)   # fourth pass -> IndexError: pop from empty list
    print(job)

Why it happens — list.pop raises IndexError on an empty list, and while True never asks whether anything is left. The same happens with pop(i) once the list has shrunk below i.

The fix

from collections import deque

queue = deque([1, 2, 3])
while queue:                 # the condition guards the pop
    print(queue.popleft())   # O(1), unlike list.pop(0)

What changed: the loop condition is the emptiness check, and deque.popleft removes the O(n) cost of pop(0).

Confirm it worked — Start from an empty queue. The loop must execute zero times instead of raising on the first pass.


10. sys.argv indexed without checking the argument count

Reproduce it

import sys

path = sys.argv[1]   # run as `python script.py` -> IndexError

Why it happens — sys.argv[0] is the script name, so a run with no arguments gives a list of length 1. Reading position 1 is out of range - the usual cause of this error in cron jobs and CI steps where an argument was dropped.

The fix

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("path")
path = parser.parse_args().path

# minimal version without argparse
# if len(sys.argv) < 2:
#     sys.exit("usage: script.py <path>")
# path = sys.argv[1]

What changed: the missing argument becomes usage output and a non-zero exit instead of a traceback.

Confirm it worked — Run the script with no arguments. argparse prints usage and exits with status 2; check it with echo $? ($LASTEXITCODE in PowerShell).


11. Index computed against an older version of the list

Reproduce it

rows = ["a", "b", "c", "d"]
selected = 3                            # chosen against the 4-item list
rows = [r for r in rows if r != "b"]    # now 3 items
print(rows[selected])                   # IndexError

Why it happens — An index is only meaningful for the exact list it was computed from. Filtering, sorting, paginating or reassigning the list invalidates stored positions while leaving the stored number looking perfectly valid.

The fix

rows = ["a", "b", "c", "d"]
selected_value = rows[3]                # keep the value, not the position
rows = [r for r in rows if r != "b"]
print(selected_value)                   # or rows.index(selected_value)

What changed: identity travels with the item instead of with its offset, so later reshaping of the list cannot break it.

Confirm it worked — Log len(rows) both where the index is stored and where it is used. If the two differ, the index is stale by construction.

A person interacts with digital code on a screen, symbolizing cybersecurity technology. ## None of Those? Narrow It Down
  1. Read the last frame of the traceback and print the container and the index immediately before that line: print(type(items), len(items), i). If len is 0, you are in the empty-collection family (causes 2, 5, 9); if i == len(items), you are in the off-by-one family (causes 1, 6, 7).
  2. Check whether the index is a literal or computed. A literal (parts[3], sys.argv[1], rows[0]) means the data is shorter than the format you assumed - go to the parsing and CLI causes. A computed index means the loop bound is wrong.
  3. Log len(items) at the top of every iteration. If the length changes during the loop, something is mutating the list mid-traversal (cause 4) or popping from it (cause 9). A constant length rules both out.
  4. Confirm that the list being indexed is the one whose length bounds the loop. for i in range(len(a)): b[i] with len(a) != len(b) is cause 6; a counter incremented inside a nested loop is cause 7.
  5. Count the subscripts on the failing expression. Two or more (grid[row][col], data["rows"][i][j]) means you must verify each level separately: print(len(grid), [len(r) for r in grid]) shows which level overflows (cause 8).
  6. Run the same input through the code one step earlier - at the API response, query result or file read - and print the raw value. An empty or short value there means the bug is upstream data, not the index, and the fix belongs in the producer or in an explicit guard.
  7. If it only fails sometimes, capture the input that fails: wrap the block in try/except IndexError that logs repr(items) and the index, then re-raise. Intermittent IndexErrors are nearly always the empty case or a race where the list is rebuilt between the length check and the lookup.

Why This Error Exists At All

A Python list is a contiguous array of pointers with a known length. When you write items[i], the interpreter compares i against that length before dereferencing anything. In C the same mistake reads whatever bytes follow the array - a silent wrong answer, or a security hole. Python makes the deliberate trade: pay a bounds check on every subscript and fail loudly at the exact instruction that was wrong. IndexError is not Python being fussy; it is the runtime refusing to invent data for a position that does not exist.

The design becomes clearer once you notice what Python doesn't raise. Slicing clamps: items[5:9] on a three-element list returns [] rather than failing, because a slice is a request for "whatever lies in this range" and an empty answer is meaningful. Indexing is a request for "the element at this position", and there is no honest empty answer - so it raises. The same split runs through the standard library: dict[k] raises KeyError while dict.get(k) returns None; list.index(x) raises ValueError while x in list returns a bool. Whenever an API has no sensible value to return, Python raises instead of handing back a sentinel you might forget to check.

That explains the family. IndexError and KeyError are both subclasses of LookupError, so except LookupError catches either when you genuinely don't care which container missed. You will meet the same mechanism as IndexError: tuple index out of range, IndexError: string index out of range and IndexError: pop from empty list - different containers, one rule: the position you named is outside what exists right now. IndexError even predates the iterator protocol as the signal for "sequence exhausted": objects that define only __getitem__ are still iterable, because Python calls them with 0, 1, 2... until one raises IndexError. The error you are debugging is literally the language's end-of-sequence marker leaking into code that asked one question too many. From above of crop black executive in suit writing on paper near laptop and diary while working at desk

Stop It From Coming Back

  • Iterate the object, not a number range. for item in items, for i, item in enumerate(items), for a, b in zip(xs, ys) - reserve range(len(...)) for the rare case where you do arithmetic on indices themselves, such as comparing items[i] with items[i + 1] (and then bound it with range(len(items) - 1)).
  • Pair lists with zip(xs, ys, strict=True) on Python 3.10 or newer, so a length mismatch raises ValueError at the pairing site instead of surfacing as an IndexError several lines later. On older interpreters, add assert len(xs) == len(ys) at the boundary where both lists arrive.
  • Parse structured text with the csv module, or with tuple unpacking (host, ts, status, path = line.split(",", 3)), which raises ValueError naming how many values were expected and how many arrived. Positional parts[n] access hides the shape mismatch until the index blows up.
  • Take CLI and environment input through argparse rather than sys.argv[n], so a missing argument produces usage text and exit status 2. The same applies to request parameters: use the framework's .get()-style accessor with a default.
  • Add a pytest case for the empty collection on every function that indexes one: @pytest.mark.parametrize("rows", [[], ["one"]]). The empty path is the single most common production IndexError and the easiest one to leave untested.
  • Use collections.deque with while queue: queue.popleft() for worker loops, and reach for contextlib.suppress(IndexError) only where "nothing there" is genuinely a no-op - never as a blanket wrapper, which converts a crash into missing data.

Related Guides

Errors You Will Probably Hit Next

  • IndexError: tuple index out of range
  • IndexError: pop from empty list
  • ValueError: not enough values to unpack (expected 3, got 1)

An IndexError is never about the index; it is about a length you assumed and never checked. Before you reach for a try/except, print the container's length and the index side by side on the failing line - that one comparison identifies which of the causes above you have in seconds. Then ask whether the code needs an index at all, because the versions written with for, enumerate and zip have no index to get wrong.

댓글

이 블로그의 인기 게시물

TypeError: Cannot read properties of undefined (reading 'map') - 11 Causes and Fixes

psql: FATAL: password authentication failed for user - 10 Causes and Fixes

Error: ERR_MODULE_NOT_FOUND: Cannot find package - 10 Causes and Fixes