Python - Deque


In Python deque is a data structure like stack and queue. It allows append and pop operations from both the ends of the queue. And that makes it different from the rest of the data structures. There are various operations which are listed below that is applicable to deque. In this article we will see the examples on each of those operations. The collections module is used to implement deque.

Deque Operations

Below are some of the useful operations carried out using deque

  • append() − This function is used to insert the value in its argument to the right end of deque.

  • appendleft() − This function is used to insert the value in its argument to the left end of deque.

  • pop() − This function is used to delete an argument from the right end of deque.

  • popleft() − This function is used to delete an argument from the left end of deque.

  • extend(iterable) − This function is used to add multiple values at the right end of deque. The argument passed is an iterable.

  • extendleft(iterable) − This function is used to add multiple values at the left end of deque. The argument passed is an iterable. Order is reversed as a result of left appends.

  • reverse() − This function is used to reverse order of deque elements.

  • rotate() − This function rotates the deque by the number specified in arguments. If the number specified is negative, rotation occurs to left. Else rotation is to right.

Example

The below program shows how the above operations are implemented using deque and the collections module.

 Live Demo

import collections
de = collections.deque([10,20,30,40])
print(de)
de.append(50)
print ("\nAppending at right the deque is : ")
print (de)
de.appendleft(60)
print ("\nAppending at left the deque is : ")
print (de)
de.pop()
print ("\nDeleting from right the deque is: ")
print (de)
de.popleft()
print ("\nDeleting from left the deque is: ")
print (de)
de.extend([70,80])
print ("\nExtending deque at end is : ")
print (de)
de.extendleft([100,90])
print ("\nExtending deque at beginning is : ")
print (de)
de.rotate(-2)
print ("\nRotating deque is : ")
print (de)
de.reverse()
print ("\nReversing deque is : ")
print (de)

Output

Running the above code gives us the following result −

deque([10, 20, 30, 40])
Appending at right the deque is :
deque([10, 20, 30, 40, 50])
Appending at left the deque is :
deque([60, 10, 20, 30, 40, 50])
Deleting from right the deque is:
deque([60, 10, 20, 30, 40])
Deleting from left the deque is:
deque([10, 20, 30, 40])
Extending deque at end is :
deque([10, 20, 30, 40, 70, 80])
Extending deque at beginning is :
deque([90, 100, 10, 20, 30, 40, 70, 80])
Rotating deque is :
deque([10, 20, 30, 40, 70, 80, 90, 100])
Reversing deque is :
deque([100, 90, 80, 70, 40, 30, 20, 10])

Updated on: 14-Feb-2020

314 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements