Reputation: 37
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 re.search(ex, records[count2].id) != None:
print records[count2].id
count2 += 1
count += 1
count2 = count + 1
Edit:
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 re.search(ex, records[bla + 1].id) != None:
print records[bla].id
Upvotes: 0
Views: 1478
Reputation: 41168
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 = rlength1.id
for i2,rlength2 in enumerate(records):
if re.search(ex, rlength2.id) != None:
print rlength2.id
Upvotes: 1
Reputation: 629
The loop should fail for i=1
. Why ?
When i=1, count2 = 2 (= count + 1, and count = 0+1 = 1)
In the inner loop, count2 goes from 2 to 2+len(records)-1-1
(since we increment after looking at the values) = len(records)
But there is no records[len(records)]
(and an index out of bound is NOT equivalent to None in python !)
Upvotes: 0