You wrote result[0] assuming the list had at least one item, but it was empty, and Python threw IndexError: list index out of range. The list might come from a filter, an API call, or a database query, all common sources of “sometimes empty” results

📌 Quick answer: Use result[0] if result else None for safe first-item access. For “next item from iterable” use next(iter(result), None). For “any matching item” use next((x for x in result if cond(x)), None). All return None on empty instead of raising.
Pattern 1: if-guard for first item
Cleanest one-liner for “give me the first item, or None if empty.”
items = filter_items() # might return []
first = items[0] if items else None
# Or with default value
first = items[0] if items else default_valuePattern 2: try/except IndexError
Useful when the access is nested or conditional and an if-guard would clutter.
try:
name = parts[0]
domain = parts[1]
except IndexError:
name, domain = None, NonePattern 3: next() with default
For iterators, generators, and filter results.
first_match = next((x for x in items if x.is_active), None)
first_item = next(iter(items), None)Pattern 4: slicing (never raises)
Slices on an empty list return an empty list, no error. Useful for “first N items” or “last item.”
first_two = items[:2] # works even if items has 0 or 1 items
last_one = items[-1:] # empty list if items is empty, else 1-element listPrevention
- Never trust upstream filters/queries to return non-empty results
- Use
if my_list:as truth test (empty list is falsy) - For “first matching” use
next((g), default)with generator expression - Slices over scalars when you need “up to N items”
Related Guides
- List index out of range (full guide)
- String index out of range
- All IndexError fixes
- Python Tutorial hub
Frequently Asked Questions
Why does Python raise IndexError on empty list?
list[i] requires position i to exist. An empty list has no valid positions (length 0, valid range is empty). Any positive integer access fails. Negative access also fails for the same reason.
What’s the safest way to get the first item from a list?
items[0] if items else default. For an iterator-friendly form: next(iter(items), default). Both return the default on empty.
Does slicing an empty list raise IndexError?
No. Slice access never raises. list[:5] on empty list returns []. list[10:20] on a 5-item list returns []. Use slices when you want ‘up to N items’ regardless of actual count.
How do I find the first item matching a condition?
next((x for x in items if x.is_active), None). The generator expression is lazy and stops at first match; the second argument is the default if no match.
Should I use try/except or if-guard for IndexError?
If-guard for simple cases (it’s faster and clearer). try/except for nested logic where you’d otherwise need multiple if-checks. Performance-wise, if-guard is faster when the access usually succeeds; try/except is faster when failures are rare and noisy.
