0

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
2
  • 5
    pop takes an index, not an item. Regardless of that, you probably shouldn't be popping things from a list while iterating over it, it usually ends in sadness. Commented Feb 16, 2016 at 2:04
  • I agree with @tzaman See this. Most of the time you can do a list comprehension to achieve the same. Commented Feb 16, 2016 at 2:21

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your patience and clear answer! It's greatly appreciated.
0

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().

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.