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 rangeCommon 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
- Add
assert results, "expected at least one result"before indexing to fail with a clear message. - Make fixtures function-scoped or reset shared state so each test starts fresh.
- 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
Python "ValueError: too many values to unpack" in CIFix "ValueError: too many values to unpack (expected 2)" in CI - a sequence had more elements than the target…
pytest-randomly Exposes Order-Dependent Test Failures in CIFix tests that fail only under pytest-randomly in CI - random test order revealed shared state, leaked fixtur…
Python "StopIteration" inside a generator in CIFix a "StopIteration" that leaks out of a generator in CI - calling next() on an exhausted iterator inside a…