Borislav Hadzhiev
Fri Apr 22 2022·2 min read
Photo by Mohamed Ahmed
The Python CSV "IndexError: list index out of range" occurs when we try to access a list at an index out of range, e.g. an empty row in a CSV file. To solve the error, check if the row isn't empty before accessing it at index, or check if the index exists in the list.
Here is an example of how the error occurs.
Assume we have the following csv
file.
first_name,last_name Alice,Smith Bob,Smith Carl,Smith
And we are trying to read it like:
import csv with open('employees.csv', newline='', encoding='utf-8') as csvfile: csv_reader = csv.reader(csvfile, delimiter=',') for row in csv_reader: # ⛔️ IndexError: list index out of range print(row[0])
row
variable stores an empty list on the second iteration.One way to solve the error is to check if the list contains any elements before accessing it at an index.
import csv with open('employees.csv', newline='', encoding='utf-8') as csvfile: csv_reader = csv.reader(csvfile, delimiter=',') for row in csv_reader: if row: # 👈️ check if row contains items print(row[0])
The if
statement checks if the list is truthy on each iteration.
All values that are not truthy are considered falsy. The falsy values in Python are:
None
and False
.0
(zero) of any numeric type""
(empty string), ()
(empty tuple), []
(empty list), {}
(empty dictionary), set()
(empty set), range(0)
(empty
range).Alternatively, you can check whether the specific index you are trying to access exists in the list.
import csv with open('employees.csv', newline='', encoding='utf-8') as csvfile: csv_reader = csv.reader(csvfile, delimiter=',') idx = 1 for row in csv_reader: if len(row) > idx: print(row[idx])
The len() function returns the length (the number of items) of an object.
The argument the function takes may be a sequence (a string, tuple, list, range or bytes) or a collection (a dictionary, set, or frozen set).
2
, then its last index is 1
(because indexes are zero-based).This means that you can check if the list's length is greater than the index you are trying to access.
Alternatively, you can use a try/except
block to handle the error.
import csv with open('employees.csv', newline='', encoding='utf-8') as csvfile: csv_reader = csv.reader(csvfile, delimiter=',') for row in csv_reader: try: print(row[1]) except IndexError: print('except block ran') continue
We try to access the list of the current iteration at index 1
, and if an
IndexError
is raised, we can handle it in the except
block or continue to
the next iteration.