1

This is a question of nested loop where I have to find the names of students in alphabetical order with 2nd lowest marks.
I am getting following error:

Traceback (most recent call last):
  File "solution.py", line 12, in <module>
    if (l[i][0]==l[0][0]):
IndexError: list index out of range

Following is my complete code.

l=list()
p=list()
q=list()
for i in range (int(raw_input())):
    p=[raw_input(),int(raw_input())]
    p.reverse()
    l.append(p)
l.sort()
print len(l)
for i in range(0,len(l)):
    print "i= ",i
    if (l[i][0]==l[0][0]):
        l.remove(l[i])
print l
for i in range(0,len(l)):
    if (l[i][0]==l[0][0]):
        q.append(l[i][1])
q.sort()

for i in range(0,len(q)):
    print q[i]

I have even printed the index which shows the values are in range. Please run the function to find the following output:

4
i=  0
i=  1
i=  2
i=  3

I will happy if I get any better method from my the community ,But my main concern is the error I am getting "Index Out of Range" .It doesn't seem right here

2
  • You're printing i, but not l. Commented Jun 24, 2016 at 5:58
  • do not remove element in loop Commented Jun 24, 2016 at 6:04

2 Answers 2

1

The problem is that you are removing items from a loop. The thumb rule is that you shall never remove items from a list while iterating over it.

I don't really understand your code right now, but you can just change the way you are doing the first loop and apply the same logic for the next ones, at least you will have what you want.

The idea here is that with the while statement, after each iteration, you will have another verification of the size of the list. Meanwhile with the for loop, only at the first time, since range will return a list and the for loop will just iterate over the list which was already created.

l=list()
p=list()
q=list()
for i in range (int(raw_input())):
    p=[raw_input(),int(raw_input())]
    p.reverse()
    l.append(p)
l.sort()
print len(l)
i = 0
while i < len(l):
    print "i= ",i
    if (l[i][0]==l[0][0]):
        l.remove(l[i])
    i += 1
print l
Sign up to request clarification or add additional context in comments.

Comments

1

You are using remove, because of that l, in some moment, have less elements than you expect.

2 Comments

But error is coming in the line before remove is executed i.e line 12 while remove is in line 13
@DhrubKumar yes, but remember that you are in a loop

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.