Dhrub Kumar
Dhrub Kumar

Reputation: 105

Nested list sorting in Python

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

Upvotes: 1

Views: 1074

Answers (2)

Ricardo Silveira
Ricardo Silveira

Reputation: 1243

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

Upvotes: 1

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

Upvotes: 1

Related Questions