0

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
5
  • I think here is problem records[count2].id), you are moving one step forward in it. Commented Jul 20, 2016 at 9:49
  • I think you have to change this line from if re.search(ex, records[count2].id) != None: to if count2 in records and re.search(ex, records[count2].id) != None: Commented Jul 20, 2016 at 9:50
  • count2 can go our of range. What are you attempting to do? Commented Jul 20, 2016 at 9:53
  • 2
    I don't think you need count and count2 at all. You can just use i and bla instead and your for loops will always remain within the range. Commented Jul 20, 2016 at 10:00
  • Thanks, I think this has done the trick Commented Jul 20, 2016 at 10:04

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

This has helped, although the reason I implemented counts was because I wanted to compare record x with x+1, x+2, ... rather than itself. But this has pointed me in the right direction. Thanks
@Thistle19 You can of course do something like records[i] and records[i+1], records[i+2], but if you do that you need to stop the loop before you go past it to avoid the IndexError, either by using something like range(len(records)-2) or by doing an if i+1 == len(records): break
0

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 !)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.