List index out of range error, but can't see why?

230 views Asked by At

This is pretty simple, but I can't figure out why I'm getting the 'list index out of range' error. I have a list called 'cycle_entries' and a list called 'rawdates' which both have a length of 132:

print len(cycle_entries)
print len(rawdates)
132
132

The output of this is also a list of length 132:

times = re.findall(dtdict['tx'], str(entries))
print len(times)
132

However, when I try to iterate from index [0] to [131] I'm getting an error.

for i in range(len(cycle_entries)):
    localtime = rawdates[i]+re.findall(dtdict['tx'], str(entries))[i]
    print localtime

IndexError: list index out of range

I can't figure out why, because this works:

test = rawdates[131]+re.findall(dtdict['tx'], str(entries))[131]
print test

Anyone know why it works normally but I get the error inside the loop?

1

There are 1 answers

0
Chen A. On

Assuming your lists contains strings, you can use zip function to iterate over both lists simultenously:

>>> times = ['1', '2', '3', '4']
>>> rawdates = ['raw1', 'raw2', 'raw3', 'raw4']
>>> for time, rawdate in zip(times, rawdates):
    localt = time + rawdate
    print localt


1raw1
2raw2
3raw3
4raw4

Note that both variables are computed before the for loop. You can also use itertools.izip which makes an iterator instead of a list.

Python's zip function docs