-1

I wrote this code to get name, student number and score and then find maximum, report and remove, but I have a problem with remove that I cannot eradicate that. When I run , I get IndexError: list index out of range line on line 37, although I cannot find what it the problem.

c=0
x=[]
y=[]
z=[]
"""o=int(input("enter menu:"))"""
while True:
    print("o=1:::add  ","o=2:::max  ","o=3:::find  ","o=4:::remove  ","o=5:::report  ","o=6:::exit")
    o=int(input("enter menu:"))
    if o==1:
        x.append(input("enter name:"))
        z.append(int(input("enter #:")))
        y.append(int(input("enter score:")))
        c+=1

    elif o==2:
        i=1
        for i in range(len(x)):
            y[i]= y[i] if y[i]>y[i-1] else y[i-1]
            """i+=1"""
        f=y[i-1]
        print("max=",y[i-1])


    elif o==3:
        n=int(input("enter number:"))
        for i in range(len(x)):
            if n==z[i]:
                print(x[i],y[i])
            else:
                print("not found")
    elif o==4:
        p=int(input("enter student number:"))
        for i in range(len(x)):
            if p==z[i]:
                x.pop(i)
                y.pop(i)
                z.pop(i)
    elif o==5:
         for i in range(len(x)):
             print("name:",x[i],"st number:",z[i],"score:",y[i])
    elif o==6:
        break
sasan
  • 19
  • 7
  • Because you are trying to access a list item that does not exist - the index is greater than the number of items in the list. Remeber that list indices are zero based. – wwii Jul 03 '16 at 21:34
  • Have you tried to debug it using a ```try/except``` block, and printing the relavent variables i the ```except``` suite? It may be a good time to get familiar with the [```pdb```](https://docs.python.org/3/library/pdb.html) module. – wwii Jul 03 '16 at 21:36
  • Can you explain more? why are you saying the index is greater than the number of items in the list? – sasan Jul 04 '16 at 11:46
  • [Modifying list while iterating [duplicate](http://stackoverflow.com/q/1637807/2823755) – wwii Jul 04 '16 at 18:09

1 Answers1

1

I think it might be because when you are deleting items, you are not breaking once an item has been deleted. Then, when you get to the end of the list(s) that use to have N elements, you only have N-1 elements left.

Add a break after:

for i in range(len(x)):
    if p==z[i]:
        x.pop(i)
        y.pop(i)
        z.pop(i)
        break  # here

Or use find instead and rewrite as:

 position = x.find(p)
 if position != -1:
     x.pop(position)
     y.pop(position)
     z.pop(position)
André Laszlo
  • 15,169
  • 3
  • 63
  • 81