Python IndexError on .split() Result (2026)

Python IndexError after calling .split() means the resulting list has fewer parts than your code expected. This is the classic “log parser breaks on the one line with a weird format” bug. Three patterns fix it safely.

Python IndexError on .split() Result (2026)

Minimal reproducer

line = "alice"
parts = line.split(',')
first_name, last_name = parts  # ValueError, not enough values
# Or:
first = parts[0]
last = parts[1]  # IndexError: list index out of range

Fix 1: Use maxsplit + default

line = "alice"
parts = line.split(',', 1) + ['']  # always at least 2 elements
first, last = parts[0], parts[1]

Fix 2: Unpacking with starred rest

line = "alice"
parts = line.split(',')
first, *rest = parts
last = rest[0] if rest else ''

Fix 3: Validate before unpacking

parts = line.split(',')
if len(parts) != 2:
    raise ValueError(f"Expected 'first,last' but got: {line!r}")
first, last = parts

Fix 4: For real CSV use the csv module

import csv
import io

line = 'alice,"hello, world",30'
reader = csv.reader(io.StringIO(line))
row = next(reader)  # ['alice', 'hello, world', '30']
# csv handles quoted commas, escaping, line continuations correctly

Common split() gotchas

Input.split(‘,’).split() (no arg)
“a,b,c”[‘a’,’b’,’c’][‘a,b,c’]
“”[”][]
“a”[‘a’][‘a’]
“,,”[”,”,”][‘,,’]
” hello “[‘ hello ‘][‘hello’]

Without an argument, .split() splits on any whitespace AND collapses multiple whitespace AND strips leading/trailing whitespace. With an explicit separator, it does exactly one split per occurrence.

Frequently Asked Questions

What is the difference between .split() and .split(‘,’)?

.split() with no argument splits on any whitespace and collapses multiple whitespace into one separator. .split(‘,’) splits on exactly comma, treats every comma as a separator, returns empty strings between consecutive commas. For CSV-like data always specify the separator.

When should I use rsplit() instead of split()?

rsplit() starts from the right. Useful when you want maxsplit on the trailing parts: “a.b.c.d”.rsplit(‘.’, 1) returns [‘a.b.c’, ‘d’], perfect for extracting file extensions. split(‘.’, 1) would give [‘a’, ‘b.c.d’].

Why does my split fail on Windows line endings?

Windows files end with \r\n, Linux/Mac with \n. If you split on \n, the \r remains as a trailing character on each line. Strip first: line.strip().split(‘,’). Or open files with newline=” and let csv module handle it.

Should I use .split() or re.split() for parsing?

.split() for a single literal separator. re.split() for regex patterns (multiple separators, whitespace+punctuation, etc.). re.split() is slower but more flexible. For CSV with quoted fields, neither works correctly; use the csv module.

Can I split on multiple delimiters at once?

Yes with re.split(r'[,;|]’, text). Or chain str.replace() to normalize first: text.replace(‘;’, ‘,’).replace(‘|’, ‘,’).split(‘,’). For parsing user-supplied data, regex split is cleaner.

Leave a Comment