Python provides the Deque
type which is used as a collection. The name Deque comes from Doubly Ended Queue
. The deque provides similar functionality to the list type but it provides faster append and pop operations which can be very useful for busy operations. The deque provides O(1) algorithm complexity which means the size of the dequeue does not affect the performance whereas the list provides O(n) algorithm complexity which increases the operation time as the list size increases.
Create Dequeue
The deque is provided via the collections
module and the collection module should be imported first and then the deque items should be provided to the deque()
constructer like a list inside square brackets. In the following example, we will create a deque that consists of numbers from 1 to 4.
import collections
d = collections.deque([1,2,3,4])
Append Item To Deque
New items can be added to the deque. This addition operation is called append and the deque type provides the append()
method for adding a new item. New items are added to the right side of the deque.
import collections
d = collections.deque([1,2,3,4])
d.append(5)
d.append(6)
Append Left Item To Deque
The append() method adds new items to the right side of the deque. But in some cases, we may need to add a new item to the left side of the deque. The appendleft()
method is used to add a new item to the left side of the deque.
import collections
d = collections.deque([1,2,3,4])
d.appendleft(0)
d.appendleft(-1)
Pop Item From Deque
The deque provides easy removal or pop operation with the pop()
method. The most right item is removed from the deque and returned as the return value.
import collections
d = collections.deque([1,2,3,4])
four = d.pop()
Pop Left Item From Deque
By default the pop operation pop and removes items from the right side. But the popleft()
method can be used to pop from the left side of the deque. The poped value is returned as return value.
import collections
d = collections.deque([1,2,3,4])
one = d.popleft()
Extended Deque
The append() method adds single item into a deque. In some cases we may need to add multipe items at once. This operation is also called as extending. The extend()
method can be used to add multiple items into a deque at once.
import collections
d = collections.deque([1,2,3,4])
one = d.extend([5,6,7])