Don Palmigiano
Don Palmigiano

Reputation: 11

Python: Why can't I pop a value from a list?

I'm not sure exactly what is happening here. I tried to be as specific as possible. Can someone tell me why this isn't working? I'm getting a "pop index out of range" error when I try to pop an item from a_list which the loop says is inside a_list. I'm learning this in a college course. Thank you! I'm really hoping this isn't a dumb question. Output below.

def k_largest(a_list,k):

    compare_list =[]

    a_list.sort()
    #print(a_list)

    for item in a_list:
        assert(type(item)==int) #the list can only contain integers

        if item in compare_list and item in a_list:
                print("pop a_list " + str(item))
                print(a_list)
                a_list.pop(item)
        else:
            if item not in compare_list:
                print("compare append " + str(item))
                compare_list.append(item)


    #print(a_list)
    #print(len(a_list))
    return a_list[len(a_list)-k]





import random
a=[]
for x in range(1,10):
    a.append(random.randint(0,100))
print (a)
k_largest(a,3)

Output:

[38, 38, 25, 25, 7, 60, 5, 35, 97]
compare append 5
compare append 7
compare append 25
pop a_list 25
[5, 7, 25, 25, 35, 38, 38, 60, 97]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-141-a73ef6b20848> in <module>()
      4     a.append(random.randint(0,100))
      5 print (a)
----> 6 k_largest(a,3)

<ipython-input-137-a9f599ea78c6> in k_largest(a_list, k)
     12                 print("pop a_list " + str(item))
     13                 print(a_list)
---> 14                 a_list.pop(item)
     15         else:
     16             if item not in compare_list:

IndexError: pop index out of range

Upvotes: 0

Views: 5764

Answers (2)

Suraj Bhatia
Suraj Bhatia

Reputation: 1323

As the Python documentation says:

array.pop([i])

Removes the item with the index i from the array and returns it. The optional argument defaults to -1, so that by default the last item is removed and returned.

You need to mention the index number for using array.pop().

Upvotes: 0

zondo
zondo

Reputation: 20336

list.pop() takes the index of an element to remove, not the item to remove. Try using list.remove() instead.

Upvotes: 3

Related Questions