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
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.
If you want, you can capture the pop value.
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 thelist.pop(index)
part , that as we mention above removes the element at indexindex
and return it , then the returned value of element passed to thelist.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 liketwice run
and that’s it.so if your target to remove element at index
index
of the list , you can do this either bylist.remove(list[index])
, orlist.pop(index)
or