Tuesday 9 March 2021

Deque in Python

 

Deque stands for Doubly Ended Queue. Deque is a generalization of stack and queue defined in Collections module. Deques support memory efficient appends and pops from either side of the deque with approximately the same O(1) time complexity in either direction.

Deques are preferred over lists because deques support thread-safe, better performance for appends and pops than lists. Time complexity to append and pop from lists take O(n) while deques offer these operations in O(1) time.

 

Creating Deque

Deque can be created using collections.deque ([iterable], maxlen) function. Here maxlen is the maximum size of the bounded deque or None if unbounded.

from collections import deque

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

print(deq)


 

If maxlen is not specified or is None, deques may grow to an arbitrary length. Otherwise, the deque is bounded to the specified maximum length. If the bounded deque is full and items are added, then a corresponding number of items are discarded from the opposite end.

from collections import deque

# 1 will be discarded because maxlen is 3

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

print(deq)

 


 

9 comments: