Thistle19 Thistle19 - 3 months ago 5x
Python Question

Python - nested for loops and index out of range

I'm rather new to Python, and am running into the following error when using a nested for loop

IndexError: list index out of range

Here is my code

count = 0
count2 = 1
rlength = range(len(records))
for i in rlength:
ex = records[count].id
for bla in rlength:
if, records[count2].id) != None:
print records[count2].id
count2 += 1
count += 1
count2 = count + 1


Fixed with the following code

rlength = range(len(records))
for i in rlength:
ex = records[i].id
for bla in rlength:
if bla + 1 < len(rlength) and, records[bla + 1].id) != None:
print records[bla].id


If I understand what you are trying to do, I'm not sure you need the count and count2 at all. I think you can just use the numbers generated by your loop. I suggest using enumerate() instead of range(len()).

for i1,rlength1 in enumerate(records):
    ex =
    for i2,rlength2 in enumerate(records):
        if, != None: