Akash Sharma Akash Sharma - 10 months ago 32
Python Question

Python : IndexError: list index out of shape

This piece of code works well when I used my earlier set of data. However Now I have added a couple more columns to the input data set and I am getting indexing errors. I am not exactly sure on how to fix this. Any inputs ? . The following code is giving me error:

with open("master_aggregated_monthly.csv", 'rb') as csvfile:
data_reader = csv.reader(csvfile, delimiter = ',', quotechar = '"')
rolling_queue = []
for row in data_reader:
if row[0].lower() == "salesforceid":

# most recent rows go in first
if len(rolling_queue) > 12:

id = row[0]
date = row[2]
if id in company_dictionary:
account = company_dictionary[id]
#See if we are at the final event
#get the final event from the list
# most recent date for data collection
if date == "6/1/2016":
new_event = event()
new_event.date = "7/1/2016"
new_event.type = "Current Period"
my_event = account.events[0]
for entry in rolling_queue:
# don't do anything if the entry in the rolling queue is not from the same account
if entry[0] != id:

nonzero_row = False
# loop through the entries in the rolling queue to find at most the last 12 months of data
for i in range(3, len(entry)):
my_event.attributes[i-3] += float(entry[i])
#handle all of the odd string things
temp = entry[i].split(' ')
if temp[0] == '':
temp = float(temp[1])
temp = float(temp[0])
my_event.attributes[i-3] += temp
# discover if this row is nonzero
if entry[i] != 0 and entry[i] != '0':
nonzero_row = True
# don't include this rown in the average if it's a zero row
if nonzero_row:
#print "Month increment"
my_event.months += 1

This code is giving me the following error

<type 'exceptions.IndexError'>
Traceback (most recent call last):
File "P:/Testing/The Scripts, JIC Test/Q4_12month.py", line 116, in main
my_event.attributes[i-3] += temp
IndexError: list index out of range


You're creating an index based off of the length of entry, but using that index in my_event.attributes:

for i in range(3, len(entry)):
        my_event.attributes[i-3] += temp

This is probably the problem, but it's kind of tough to tell what your code is doing. Generally, you'll only want to use an index on whatever object the index was created with / whatever object the index is supposed to refer to (in this case entry).