Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Comprehensions in Python
Next article icon

Deque Implementation in Python

Last Updated : 13 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A deque (double-ended queue) is a data structure that allows insertion and deletion from both the front and rear in O(1) time in optimized implementations. Unlike regular queues, which are typically operated on using FIFO (First In, First Out) principles, a deque supports both FIFO and LIFO (Last In, First Out) operations.

Deque in Python Library

Deque in Python is implemented using a doubly linked list, making append and pop operations from both ends O(1) (constant time). Unlike Python’s built-in list (which uses a dynamic array), deque does not require shifting elements when inserting/deleting at the front.

Implementing Your Own Deque in Python

Different methods to implement Deque are:

1. Using Doubly Linked List

A deque (double-ended queue) is a data structure that allows insertion and deletion from both the front and rear in O(1) time. Python’s collections.deque is implemented using a doubly linked list. A Doubly Linked List (DLL) allows efficient insertion and deletion at both ends in O(1) time. Each node contains three parts:

  • Data: Stores the value
  • next: Pointer to the next node
  • prev: Pointer to the previous node

Operations:

1. Append at the rear (append_rear(item) ): Adds an item at the rear. If the deque is empty, it initializes both front and rear to the new node. Otherwise, it links the current rear to the new node and updates the rear pointer to the new node.

2. Insert at the front (insert_front(item) ): Adds an item at the front. If the deque is empty, it initializes both front and rear to the new node. Otherwise, it links the new node to the current front and updates the front pointer to the new node.

3. Remove from the rear (remove_rear() ): Removes an item from the rear. If the deque has only one item, it sets both front and rear to None. If there are multiple items, it moves the rear pointer to the previous node and updates the next pointer of the new rear to None.

4. Remove from the front (remove_front() ): Removes an item from the front. If the deque has only one item, it sets both front and rear to None. If there are multiple items, it moves the front pointer to the next node and updates the prev pointer of the new front to None.

Time Complexity : All operations (append, insert, remove) are O(1), since adding or removing elements only requires adjusting a few pointers.

Pros of Using a Doubly Linked List for Deque

  1. Efficient Insertions/Deletions (O(1)): No need to shift elements like in arrays.
  2. Dynamic Size: No need to predefine a fixed size (unlike circular array-based deque).
  3. Supports Bi-Directional Traversal: Can traverse from front to rear and rear to front easily.

No Memory Waste: Unlike an array, no extra memory is allocated beforehand.

Challenges of Using a Doubly Linked List for Deque

  1. Extra Memory for Pointers: Each node requires two extra pointers (next & prev).
  2. More Complex Implementation: Requires manual memory management and careful handling of pointers.
  3. Cache Unfriendliness: Unlike an array-based deque, linked lists are not cache-efficient, as elements are stored at non-contiguous memory locations.

To explore in detail refer - Implementation of Deque using Doubly Linked List in Python 

2. Using List and Circular List

Python lists can be used to simulate a deque, but since lists are dynamic arrays, operations at the beginning of the list are inefficient because elements need to be shifted. Below are the basic operations:

Operations

1. Append at the rear (list.append(item) → O(1) ): This operation adds an item to the end (rear) of the list. Time Complexity is O(1).

2. Insert at the front (list.insert(0, item) → O(n) ): This operation inserts an item at the front (beginning) of the list. Time Complexity is O(n).

3. Remove from rear (list.pop() → O(1) ): This operation removes and returns the last item from the list (the rear of the deque). Time Complexity is O(1).

4. Remove from front (list.pop(0) → O(n) ): This operation removes and returns the first item from the list (the front of the deque). Time Complexity is O(n).

Using a normal Python list makes front operations inefficient because shifting elements takes O(n) time. To overcome this, we use a circular array approach, where the deque operates in a fixed-size list, and elements wrap around when they reach the end.

1. Efficient Insertions & Deletions

  • Rear insertion is done at (front + size) % capacity, ensuring the elements wrap around.
  • Front insertion moves the front pointer backward using (front - 1) % capacity.
  • Deletions adjust the front or rear index dynamically, avoiding unnecessary shifting.

2. Fixed Capacity & Wrapping Around

  • When inserting, we don't shift elements; instead, we update indices using the modulus operator (%).
  • This ensures that if the deque reaches the end of the array, it wraps around to the beginning.

3. Displaying Elements

  • Since the deque is circular, elements are accessed using modulus arithmetic (front + i) % capacity to print them in the correct order.

Pros of Using a Circular List for Deque

  1. Efficient Insertions/Deletions (O(1)): No shifting is required, making operations faster.
  2. Bi-Directional Traversal: Can traverse the list in both forward and backward directions efficiently.
  3. No Fixed Size Limitation: Unlike an array-based deque, it can dynamically grow and shrink.
  4. Circular Nature Eliminates Edge Cases: No need to handle special cases for front or rear as they wrap around automatically.
  5. Efficient Memory Utilization: No wasted memory slots, as seen in array-based implementations.

Challenges of Using a Circular List for Deque

  1. Extra Memory Overhead: Each node requires two extra pointers (next & prev), increasing memory usage.
  2. Complex Implementation: Managing circular links correctly requires careful handling, especially during insertions and deletions.
  3. Cache Inefficiency: Unlike array-based deques, linked lists suffer from poor cache locality, affecting performance in large datasets.
  4. Higher Maintenance Cost: Requires manual pointer management to prevent dangling pointers and memory leaks in languages without garbage collection.

To explore in detail refer - Implementation of Deque Using List in Python


Next Article
Comprehensions in Python

B

brijkan3mz4
Improve
Article Tags :
  • Python
  • DSA
  • Python-DSA
Practice Tags :
  • python

Similar Reads

  • Stack Implementation using Deque
    A doubly ended queue or deque allows insertion and deletion at both ends. In a stack, we need to do insertions and deletions at one end only. We can use either end of deque (front or back) to implement a stack, In the below implementation, we use back (or rear) of stack to do both insertions and del
    2 min read
  • Deque in Python
    A deque stands for Double-Ended Queue. It is a data structure that allows adding and removing elements from both ends efficiently. Unlike regular queues, which are typically operated on using FIFO (First In, First Out) principles, a deque supports both FIFO and LIFO (Last In, First Out) operations.
    6 min read
  • Comprehensions in Python
    Comprehensions in Python provide a concise and efficient way to create new sequences from existing ones. They enhance code readability and reduce the need for lengthy loops. Python supports four types of comprehensions: List ComprehensionsDictionary ComprehensionsSet ComprehensionsGenerator Comprehe
    4 min read
  • Implementing LRU Cache Decorator in Python
    LRU is the cache replacement algorithm that removes the least recently used data and stores the new data. Suppose we have a cache space of 10 memory frames. And each frame is filled with a file. Now if we want to store the new file, we need to remove the oldest file in the cache and add the new file
    3 min read
  • Python Built in Functions
    Python is the most popular programming language created by Guido van Rossum in 1991. It is used for system scripting, software development, and web development (server-side). Web applications can be developed on a server using Python. Workflows can be made with Python and other technologies. Databas
    6 min read
  • Deque vs List in Python
    Python provides multiple data structures to handle collections of data, with list and deque (double-ended queue) being two commonly used structures, each offering unique advantages depending on the operation at hand. List is a dynamic array that supports indexing and slicing.Deque is a doubly linked
    4 min read
  • Internal implementation of Data Structures in Python
    Python provides a variety of built-in data structures, each with its own characteristics and internal implementations optimized for specific use cases. In this article we are going to discuss about the most commonly used Data structures in Python and a brief overview of their internal implementation
    3 min read
  • Dictionaries in Python
    A Python dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any data type and can be duplicated, whereas keys can't be repeated and must be immutable. Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier t
    5 min read
  • Matrix manipulation in Python
    In python matrix can be implemented as 2D list or 2D Array. Forming matrix from latter, gives the additional functionalities for performing various operations in matrix. These operations and array are defines in module "numpy". Operation on Matrix : 1. add() :- This function is used to perform eleme
    4 min read
  • Python compile() Function
    Python is a high-level, general-purpose, and very popular programming language. In this article, we will learn about the Python compile() function. Python compile() Function SyntaxPython compile() function takes source code as input and returns a code object that is ready to be executed and which ca
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences