16

Is there any way to remove an item in deque by index?

dq = deque(['a','b','c'])
dq.removeByIndex(1) 
#output deque(['b', 'c'])

I only see remove by value in the doc. Also, I know I can just pop it i times and then put it back, but it doesn't look pretty.

deque

Denly
  • 899
  • 1
  • 10
  • 21

1 Answers1

27

You can try this :

from collections import deque
deq = deque([1, 2, 3, 4])

del deq[1]
print(deq)

Output:

deque([1, 3, 4])
  • @Denly: Not necessary. `deque`s are documented to be [mutable sequences](https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableSequence), and *all* mutable sequences support this behavior (via `__delitem__`). `deque`s are also explicitly documented to support subscript operations (of which `del` of a subscript is just one more use case). Same thing applies to mutable mappings (e.g. `dict` and `dict`-like things). – ShadowRanger May 25 '18 at 01:20
  • 3
    What is the complexity? `O(n)` or `O(1)` – kaushalpranav Jul 20 '21 at 10:00
  • 1
    Unfortunately, it is `O(n)`: https://stackoverflow.com/questions/58152201/time-complexity-deleting-element-of-deque – Matias Jan 07 '22 at 18:50
  • 1
    Deque is a double linked list internally. So any action require index is O(n). So del deq[1] is O(n). However, pop and append is O(1). This is opposite to the normal list which is a dynamic sized array. Accessing index is O(1), pop and append is O(n). – Tim Hong May 31 '22 at 21:04
  • As shown in this document (https://wiki.python.org/moin/TimeComplexity), the append and pop last of list are O(1). – David H. J. Dec 21 '22 at 09:23