Skip to content
Latchkey

Python "IndexError: list index out of range" in CI

Subscripting a list with an index beyond its last position raises IndexError. In test suites this commonly means the fixture or query returned fewer rows than the test hard-codes.

What this error means

A test fails with "IndexError: list index out of range" on a line like results[0] or rows[2]. It can be order-dependent or tied to a fixture that returned an empty list.

pytest
    first = results[0]
IndexError: list index out of range

Common causes

The collection is empty or shorter than assumed

A filter, query, or upstream step returned no items, so [0] is invalid.

Shared state from another test changed the data

A prior test mutated or consumed the fixture, leaving fewer elements than this test expects.

How to fix it

Assert length before indexing

  1. Add assert results, "expected at least one result" before indexing to fail with a clear message.
  2. Make fixtures function-scoped or reset shared state so each test starts fresh.
  3. If the test depends on data created by another test, give it its own setup.
Python
assert len(results) >= 1, f"expected results, got {results!r}"
first = results[0]

How to prevent it

  • Use function-scoped fixtures to avoid cross-test data bleed.
  • Guard indexing with length assertions in tests.
  • Run the suite with pytest-randomly to surface order dependence early.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →