This is one of those embarassing pieces of code that simply needs a second pair of eyes to spot the “obvious” mistake. I am processing a list of lists, and for some reason, I am hitting a ‘List Index out of range’ erorr – and I can’t spot it despite peering at the screen for a while.
Here is the snippet:
def group_ldata(data, freq, normal_grouping = True):
if freq > 1 and len(data) > (SOME_SANITY_FACTOR*freq):
i, output, subset, lastpos = (0, [],[], len(data)-freq)
if not normal_grouping:
for i in range(lastpos):
pass
else:
while True:
subset = data[i:freq]
#print subset
firstrow = subset[0]
lastrow = subset[-1]
output.append((firstrow[0], firstrow[1], lastrow[2]))
i += freq
if i >= lastpos:
break
return output
else:
return data
Here’s some sample data to boot:
>>> a =[]
>>> a.append(range(0,5))
>>> a.append(range(5,10))
>>> a.append(range(10,15))
>>> a.append(range(15,20))
>>> a.append(range(20,25))
>>> a.append(range(25,30))
>>> a.append(range(30,35))
Here is the result when I run it:
>>> b = group_ldata(a,2)
[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
[]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 11, in group_ldata
IndexError: list index out of range
Can anyone spot what is causing the error?
I am not sure what you are trying to do. But, the reason for the error is obvious.
In the beginning, you do
i=0.Then, later in the
while Trueloop, you doi += freq. So, now iequalsfreq.Now, when the
while Trueloop runs again (2nd iteration), in the linesubset = data[i:freq], subset will be equal to a list with lenght 0. And you are trying to access the first element of that. Makes sense?