The Wayback Machine - https://web.archive.org/web/20241118235753/https://www.geeksforgeeks.org/deque-in-python/
Open In App

Deque in Python

Last Updated : 20 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Deque (Doubly Ended Queue) in Python is implemented using the module “collections“. Deque is preferred over a list in the cases where we need quicker append and pop operations from both the ends of the container, as deque provides an O(1) time complexity for append and pop operations as compared to a list that provides O(n) time complexity.

Types of Restricted Deque Input

  • Input Restricted Deque:  Input is limited at one end while deletion is permitted at both ends.
  • Output Restricted Deque: output is limited at one end but insertion is permitted at both ends.

Example: Python code to demonstrate deque 

Python3
from collections import deque 
    
# Declaring deque 
queue = deque(['name','age','DOB'])  
    
print(queue)

Output
deque(['name', 'age', 'DOB'])

Operations on deque 

Example 1: Appending Items Efficiently

  • append():- This function is used to insert the value in its argument to the right end of the deque.
  • appendleft():- This function is used to insert the value in its argument to the left end of the deque.
Python
# importing "collections" for deque operations
import collections

# initializing deque
de = collections.deque([1, 2, 3])
print("deque: ", de)

# using append() to insert element at right end
# inserts 4 at the end of deque
de.append(4)

# printing modified deque
print("\nThe deque after appending at right is : ")
print(de)

# using appendleft() to insert element at left end
# inserts 6 at the beginning of deque
de.appendleft(6)

# printing modified deque
print("\nThe deque after appending at left is : ")
print(de)

Output
deque:  deque([1, 2, 3])

The deque after appending at right is : 
deque([1, 2, 3, 4])

The deque after appending at left is : 
deque([6, 1, 2, 3, 4])

Refer end for complexity analysis.

Example 2: Popping Items Efficiently

  • pop():- This function is used to delete an argument from the right end of the deque.
  • popleft():- This function is used to delete an argument from the left end of the deque.
Python3
# importing "collections" for deque operations
import collections

# initializing deque
de = collections.deque([6, 1, 2, 3, 4])
print("deque: ", de)

# using pop() to delete element from right end
# deletes 4 from the right end of deque
de.pop()

# printing modified deque
print("\nThe deque after deleting from right is : ")
print(de)

# using popleft() to delete element from left end
# deletes 6 from the left end of deque
de.popleft()

# printing modified deque
print("\nThe deque after deleting from left is : ")
print(de)

Output
deque:  deque([6, 1, 2, 3, 4])

The deque after deleting from right is : 
deque([6, 1, 2, 3])

The deque after deleting from left is : 
deque([1, 2, 3])

Refer end for complexity analysis.

Example 3: Accessing Items in a deque

  • index(ele, beg, end):- This function returns the first index of the value mentioned in arguments, starting searching from beg till end index.
  • insert(i, a) :- This function inserts the value mentioned in arguments(a) at index(i) specified in arguments.
  • remove():- This function removes the first occurrence of the value mentioned in arguments.
  • count():- This function counts the number of occurrences of value mentioned in arguments.
Python3
# Python code to demonstrate working of 
# insert(), index(), remove(), count()

# importing "collections" for deque operations
import collections

# initializing deque
de = collections.deque([1, 2, 3, 3, 4, 2, 4])

# using index() to print the first occurrence of 4
print ("The number 4 first occurs at a position : ")
print (de.index(4,2,5))

# using insert() to insert the value 3 at 5th position
de.insert(4,3)

# printing modified deque
print ("The deque after inserting 3 at 5th position is : ")
print (de)

# using count() to count the occurrences of 3
print ("The count of 3 in deque is : ")
print (de.count(3))

# using remove() to remove the first occurrence of 3
de.remove(3)

# printing modified deque
print ("The deque after deleting first occurrence of 3 is : ")
print (de)

Output
The number 4 first occurs at a position : 
4
The deque after inserting 3 at 5th position is : 
deque([1, 2, 3, 3, 3, 4, 2, 4])
The count of 3 in deque is : 
3
The deque after deleting first occurrence of 3 is : 
deque([1, 2, 3, 3, 4, 2, 4])

Refer end for complexity analysis.

Example 4: Size of a deque

  • len(dequeue):- Return the current size of the dequeue.
Python
# Python Program to demonstrate 
# how to find size of a Dequeue
from collections import deque

# initializing deque
de = deque([1, 2, 3, 4, 5, 6])
print("Current Deque: ", de)

# printing current size of deque
print(f"Size of Deque: {len(de)}")

# using pop() to delete element from right end
# deletes 6 from the right end of deque
de.pop()

# printing modified deque
print("\nThe deque after deleting from right is: ", end = '')
print(de)

# printing current size of deque
print(f"Size of Deque: {len(de)}")

# This code is contributed by Susobhan Akhuli

Output
Current Deque:  deque([1, 2, 3, 4, 5, 6])
Size of Deque: 6

The deque after deleting from right is: deque([1, 2, 3, 4, 5])
Size of Deque: 5

Refer end for complexity analysis.

Example 5: Front and Back of a deque

  • Deque[0] :- We can access the front element of the deque using indexing with de[0].
  • Deque[-1] :- We can access the back element of the deque using indexing with de[-1].
Python
# Python Program to demonstrate
# accessing the front and back of a Deque

from collections import deque

# initializing deque
de = deque([1, 2, 3, 4, 5, 6])
print("Current Deque: ", de)

# Accessing the front element of the deque
print("Front element of the deque:", de[0])

# Accessing the back element of the deque
print("Back element of the deque:", de[-1])

# This code is contributed by Susobhan Akhuli

Output
Current Deque:  deque([1, 2, 3, 4, 5, 6])
Front element of the deque: 1
Back element of the deque: 6

Refer end for complexity analysis.

Example 6: Different operations on deque

  • extend(iterable):- This function is used to add multiple values at the right end of the deque. The argument passed is iterable.
  • extendleft(iterable):- This function is used to add multiple values at the left end of the deque. The argument passed is iterable. Order is reversed as a result of left appends.
  • reverse():- This function is used to reverse the 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 the left. Else rotation is to right.
Python3
# Python code to demonstrate working of 
# extend(), extendleft(), rotate(), reverse()

# importing "collections" for deque operations
import collections

# initializing deque
de = collections.deque([1, 2, 3,])

# using extend() to add numbers to right end 
# adds 4,5,6 to right end
de.extend([4,5,6])

# printing modified deque
print ("The deque after extending deque at end is : ")
print (de)

# using extendleft() to add numbers to left end 
# adds 7,8,9 to left end
de.extendleft([7,8,9])

# printing modified deque
print ("The deque after extending deque at beginning is : ")
print (de)

# using rotate() to rotate the deque
# rotates by 3 to left
de.rotate(-3)

# printing modified deque
print ("The deque after rotating deque is : ")
print (de)

# using reverse() to reverse the deque
de.reverse()

# printing modified deque
print ("The deque after reversing deque is : ")
print (de)

Output
The deque after extending deque at end is : 
deque([1, 2, 3, 4, 5, 6])
The deque after extending deque at beginning is : 
deque([9, 8, 7, 1, 2, 3, 4, 5, 6])
The deque after rotating deque is : 
deque([1, 2, 3, 4, 5, 6, 9, 8, 7])
The deque after reversing deque is : 
deque([7, 8, 9, 6, 5, 4, 3, 2, 1])

Refer end for complexity analysis.

Complexity Analysis:

Methods

Time Complexity

Auxiliary Space

append()

O(1)

O(1)

appendleft()

O(1)

O(1)

pop()

O(1)

O(1)

popleft()

O(1)

O(1)

index(ele, beg, end)

O(N)

O(1)

insert(i, a)

O(N)

O(1)

remove()

O(N)

O(1)

count()

O(N)

O(1)

len(dequeue)

O(1)

O(1)

Deque[0]

O(1)

O(1)

Deque[-1]

O(1)

O(1)

extend(iterable)

O(K)

O(1)

extendleft(iterable)

O(K)

O(1)

reverse()

O(N)

O(1)

rotate()

O(K)

O(1)

 

Deque in Python – FAQs

Why use deque instead of list in Python?

deque (double-ended queue) in Python, from the collections module, provides optimized operations for appending and popping elements from both ends of the sequence. Compared to list, which provides constant time complexity for append operations (amortized O(1)), deque offers consistent O(1) time complexity for append and pop operations from both ends. This makes deque suitable for scenarios where efficient appends and pops are required from both ends of the sequence, such as implementing queues and stacks.

Is deque better than queue in Python?

In Python, queue is a module that provides different types of queues like Queue, LifoQueue, and PriorityQueue, built on top of deque or list. deque itself is not better or worse than queue, but rather serves as a fundamental component that can be used to implement efficient queues (Queue), stacks (LifoQueue), and double-ended queues (deque).

Why is deque faster than queue?

deque itself is not faster than queue because deque is often used as the underlying data structure to implement queues (Queue), stacks (LifoQueue), and double-ended queues (deque) in Python. The efficiency of operations (such as append and pop) depends on the specific implementation and usage context rather than deque being inherently faster than queue.

Why is deque faster than stack?

deque is not necessarily faster than a stack (LifoQueue) because both can be implemented using deque as the underlying data structure. However, if comparing deque to a straightforward list-based stack implementation (list used as a stack), deque may offer faster performance for pop and append operations due to its optimized internals for these operations.

What are the two types of deque?

In Python’s collections module, there are two primary types of deque:

  • deque: A general-purpose double-ended queue.
  • deque(maxlen=N): A bounded deque that restricts the maximum number of elements (N) it can hold. When new items are added and the deque is full, the oldest items are automatically removed to accommodate the new items.

What is the difference between a simple queue and deque?

A simple queue, such as those implemented using queue.Queue in Python, typically refers to a FIFO (First-In-First-Out) data structure where elements are inserted at the rear and removed from the front. deque, on the other hand, supports efficient insertion and deletion operations from both ends (front and rear) of the queue. It can function as a double-ended queue (collections.deque) or as a general-purpose data structure that can mimic a FIFO queue (queue.Queue) or LIFO stack (queue.LifoQueue) depending on how it’s used.



Previous Article
Next Article

Similar Reads

deque::at() and deque::swap() in C++ STL
Deque or Double ended queues are sequence containers with the feature of expansion and contraction on both the ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. deque::at()at() function is us
4 min read
deque::clear() and deque::erase() in C++ STL
Deque or Double-ended queues are sequence containers with the feature of expansion and contraction on both ends. They are similar to vectors, but are more efficient in the case of insertion and deletion of elements at the end, and also at the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. deque::clear() The clear()
5 min read
deque::operator= and deque::operator[] in C++ STL
Deque or Double ended queues are sequence containers with the feature of expansion and contraction on both the ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. deque::operator= This operator
4 min read
Difference between Queue and Deque (Queue vs. Deque)
Queue: The queue is an abstract data type or linear data structure from which elements can be inserted at the rear(back) of the queue and elements can be deleted from the front(head) of the queue. The operations allowed in the queue are:insert an element at the reardelete element from the frontget the last elementget the first elementcheck the size
3 min read
Deque::front() and deque::back() in C++ STL
Deque or Double Ended queues are sequence containers with the feature of expansion and contraction on both ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also at the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed in the deque. deque::front()fron
4 min read
How to get the first and last elements of Deque in Python?
Deque is a Double Ended Queue which is implemented using the collections module in Python. Let us see how can we get the first and the last value in a Deque. Method 1: Accessing the elements by their index. The deque data structure from the collections module does not have a peek method, but similar results can be achieved by fetching the elements
2 min read
Difference between queue.queue vs collections.deque in Python
Both queue.queue and collections.deque commands give an idea about queues in general to the reader but, both have a very different application hence shouldn't be confused as one. Although they are different and used for very different purposes they are in a way linked to each other in terms of complete functionality. Before we jump into what they a
3 min read
How to check if a deque is empty in Python?
In this article, we are going to know how to check if a deque is empty in Python or not. Python collection module provides various types of data structures in Python which include the deque data structure which we used in this article. This data structure can be used as a queue and stack both because it allows the user to insert and delete the elem
3 min read
IndexError: pop from Empty Deque in Python
In Python, the IndexError: pop from an empty deque is an error that occurs when trying to use the pop() method on an empty deque. A deque (double-ended queue) is a versatile data structure that allows efficient addition and removal of elements from both ends. This article explores the causes of the error, provides examples of its occurrence, and of
4 min read
Python - Queue.LIFOQueue vs Collections.Deque
Both LIFOQueue and Deque can be used using in-built modules Queue and Collections in Python, both of them are data structures and are widely used, but for different purposes. In this article, we will consider the difference between both Queue.LIFOQueue and Collections.Deque concerning usability, execution time, working, implementation, etc. in Pyth
3 min read
Deque | Set 1 (Introduction and Applications)
Deque or Double Ended Queue is a generalized version of Queue data structure that allows insert and delete at both ends. Operations on Deque: Below is a table showing some basic operations along with their time complexity, performed on deques. Operation Description Time Complexitypush_front() Inserts the element at the beginning. O(1) push_back() A
5 min read
Segregate even and odd nodes in a Linked List using Deque
Given a Linked List of integers. The task is to write a program to modify the linked list such that all even numbers appear before all the odd numbers in the modified linked list. It is not needed to keep the order of even and odd nodes the same as that of the original list, the task is just to rearrange the nodes such that all even valued nodes ap
10 min read
Deque meaning in DSA
Deque, which stands for Double Ended Queue, is a special type of queue that allows adding and removing elements from both front and rear ends. Characteristics: of Deque:Dynamic size: The size of a deque can change dynamically during the execution of a program.Linear: Elements in a deque are stored linearly and can be accessed in a sequential manner
2 min read
Difference between Queue and Deque in C++
Queue: A Queue is a linear data structure that follows a First In First Out (FIFO) order in which the operations are performed. It is a type of container adaptor where elements are inserted into one end of the container and deleted from the other. Functions: empty(): Tests whether the queue is empty.size(): Returns the unsigned int, size of the que
4 min read
Deque of Pairs in C++ with Examples
What is a deque? In C++, the deque is a sequence container and it is also known by the name, double-ended queue. As the name implies, a deque allows insertion and deletion from both ends. Although a deque is similar to a vector, deques are more efficient compared to vectors. In vectors, contiguous storage allocation is guaranteed but this might not
5 min read
Deque of Tuples in C++ with Examples
What is deque? In C++, a deque is a sequence container and it is also known by the name, double-ended queue. As the name implies, a deque allows insertion and deletion from both ends. Although a deque is similar to a vector, deques are more efficient compared to vectors. In vectors, contiguous storage allocation is guaranteed but this might not be
8 min read
Applications, Advantages and Disadvantages of Deque
Deque is a type of queue in which insert and deletion can be performed from either front or rear. It does not follow the FIFO rule. It is also known as double-ended queue Operations on Deque: Deque consists of mainly the following operations: Insert FrontInsert RearDelete FrontDelete Rear 1. Insert at the Front: This operation is used to add an ele
4 min read
Circular Subsequence Shift with Deque
Given a string S of lowercase English letters, each character is linked to one of T's unique identifiers. Specifically, character positions are associated with identifiers from 1 to T. For each identifier IDi (ranging from 1 to M), perform a clockwise/right circular shift by 1 on the portion of string S linked to identifier IDi. This operation repl
10 min read
Implementation of Deque using doubly linked list
Deque or Double Ended Queue is a generalized version of Queue data structure that allows insert and delete at both ends. In previous post Implementation of Deque using circular array has been discussed. Now in this post we see how we implement Deque using Doubly Linked List. Operations on Deque :Mainly the following four basic operations are perfor
15+ min read
Deque in C++ Standard Template Library (STL)
Double-ended queues are sequence containers with the feature of expansion and contraction on both ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements. Unlike vectors, contiguous storage allocation may not be guaranteed. Double Ended Queues are basically an implementation of the data structure doub
4 min read
Implementation of Deque using circular array
Implement a deque Using a circular array: Deque or Double Ended Queue is a generalized version of the Queue data structure that allows insert and delete at both ends Operations on Deque: Mainly the following four basic operations are performed on queue: insertFront(): Adds an item at the front of Deque.insertRear(): Adds an item at the rear of Dequ
15+ min read
Implement Stack and Queue using Deque
Deque also known as double ended queue, as name suggests is a special kind of queue in which insertions and deletions can be done at the last as well as at the beginning. A link-list representation of deque is such that each node points to the next node as well as the previous node. So that insertion and deletions take constant time at both the beg
15 min read
Deque interface in Java with Example
Let us start with a simple Java code snippet demonstrating creating a Deque in Java. [GFGTABS] Java import java.util.ArrayDeque; import java.util.Deque; public class DequeCreation { public static void main(String args[]) { // Create a Deque of Strings Deque<String> deque = new ArrayDeque<>(); // here, we can write all the operations in
10 min read
Reverse a Linked List in groups of given size using Deque
Given a Singly linked list containing n nodes. The task is to reverse every group of k nodes in the list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should be considered as a group and must be reversed. Examples: Input: head: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL, k = 2 Output: head: 2 -> 1 -
8 min read
Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
2 min read
Python | Add Logging to Python Libraries
In this article, we will learn how to add a logging capability to a library, but don’t want it to interfere with programs that don’t use logging. For libraries that want to perform logging, create a dedicated logger object, and initially configure it as shown in the code below - Code #1 : C/C++ Code # abc.py import logging log = logging.getLogger(_
2 min read
Python | Index of Non-Zero elements in Python list
Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming. Let's discuss a shorthand by which we can perform this particular task. Method : Using enumerate() + list comprehension This method can be
6 min read
MySQL-Connector-Python module in Python
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command. In this article, we will be disc
2 min read
Practice Tags :
three90RightbarBannerImg