Search code examples
pythondeque

deleting items from the back of a deque


I'm using a dequeue in Python. I know that for deleting a certain item from a dequeue I can do it by its index. like this:

from collections import deque
deq = deque([1, 2, 3, 4, 5, 6, 7, 8])
del deq[1]

Now I want to delete multiple items from the end of the dequeue, so I use this:

from collections import deque

deq = deque([1, 2, 3, 4, 5, 6, 7, 8])
for i in range(1, 5):
    del deq[-i]
print(deq)

I expect the new deq to be deq=[1, 2, 3, 4] but the output is deq = [1, 3, 5, 7]. Why is this happening?


Solution

  • the last element has index -1. When you delete the last element, the next element to delete still has index -1

    from collections import deque
    
    deq = deque([1, 2, 3, 4, 5, 6, 7, 8])
    for i in range(1, 5):
        del deq[-1]
    

    Maybe a nicer alternative is

    deq.pop()
    

    which pops the last element (and returns it)