skip to Main Content

I’m trying to make a program remove strings from a list by index value, but it keeps running remove() twice at a time.

For example trying to remove the second item from a list of identical strings:

list = ['banana', 'banana', 'banana']
index = 1
list.remove(list.pop(index))

then list only contains ['banana'].

And:

list = ['apple', 'banana', 'apple', 'apple', 'banana', 'banana']
index = 1
list.remove(list.pop(index))

returns
['apple', 'apple', 'apple', 'banana']

so it seems that for whatever reason the removal is running twice but the list.pop(index) only runs the first time. It still occurs when I break the list.pop(index) into a separate variable

Is this possibly a bug with visual studio code? I don’t see why the remove() function would run twice every time.

2

Answers


  1. You are removing the item twice.

    In DataStructures you can see that pop() removes the item and returns it. Then you are passing that returned item to remove() function. So yes, you are removing it twice.

    If you use pop() the list will be modified inplace.

    list = ['banana', 'banana', 'banana']
    list.pop(1)
    print(list)
    >>> ['banana', 'banana']
    

    If you want, you can capture the pop value.

    list = ['banana', 'banana', 'banana']
    x = list.pop(1)
    print(list)
    >>> ['banana', 'banana']
    
    print(x)
    >>> 'banana'
    
    Login or Signup to reply.
  2. The point here is that you access the desired element using .pop() method that itself removes/pops the element at the given index ( default the last index ) and return it.

    so this list.remove(list.pop(index)) , executes from in to out first it applies the list.pop(index) part , that as we mention above removes the element at index index and return it , then the returned value of element passed to the list.remove(value) so it by it’s rule go and remove the first occurance of this element in list so you face this behaviour that seems like twice run and that’s it.

    so if your target to remove element at index index of the list , you can do this either by list.remove(list[index]) , or list.pop(index)

    list = ['banana', 'banana', 'banana']
    index = 1
    list.remove(list[index])
    # list become ['banana', 'banana']
    

    or

    list = ['banana', 'banana', 'banana']
    index = 1
    list.pop(index)
    # list become ['banana', 'banana']
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search