Deque (maxlen=n) creates a fixed-length queue that automatically moves except for the oldest record when a new record is added and the queue is full.
1 from collections import deque 2 d=deque ( Maxlen=3) 3 d.append (1" 4 d.append (2 5 d.append (3 6 print (d) 7 print ( Type (d)) 8 d.append (4 9 print (d)
View Code
The output is as follows:
Deque ([1, 2, 3], maxlen=3)
<class ' Collections.deque ' >
Deque ([2, 3, 4], maxlen=3)
Although the functionality of the deque can be accomplished through list operations (Append, Del), this solution to the queue is much more elegant and runs faster. If Deque does not specify a queue length, it will get a queue with no bounds and can perform add and eject operations at both ends, for example:
1 fromCollectionsImportdeque2D=deque ()3D.append (1)4D.append (2)5D.append (3)6 Print(d)7D.appendleft (4)8 Print(d)9 D.pop ()Ten Print(d) One D.popleft () A Print(d)
View Code
The output is as follows:
Deque ([1, 2, 3])
Deque ([4, 1, 2, 3])
Deque ([4, 1, 2])
Deque ([1, 2])
The complexity of adding or ejecting elements from both ends of the queue is O (1). This is different from the list, when inserting or removing elements from the head of the list, the complexity of the list is O (N)
Python Basics: The use of deque