Python deque: difference from list?

Deque is a doubly linked list while List is just an array.

Randomly accessing an object at index i is O(n) for Deque but O(1) for List.

Fast insertions and deletions at the beginning is the biggest advantage of Deque. Fast random reads is the advantage of List.

If insertions and deletions happen randomly in the middle of the container, Deque will have to find the node (O(n), then insert a new node (O(1)), while List having to move some nodes (O(n)).

They both have their use cases.


A list is supposed to be iterated and/or randomly accessed. Typical usage: store a collection of homogeneous data items.

A queue is designed to be operated at the end/beginning. Typical usage: store data with priority information, facilitating a wide/depth-first search.


A deque is more efficient for pushing and popping from the ends. Read on, and below the list of methods you'll find:

Indexed access is O(1) at both ends but slows to O(n) in the middle. For fast random access, use lists instead.

Adding to or removing from the beginning of a list is O(n), but fetching elements from the middle is O(1). For a deque, the reverse is true.

So generally you only want a deque when you don't care about what's in the middle; you want to feed it things in some order and then get them back in that order elsewhere.

Tags:

Python