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:
ChainMap in Python
Next article icon

Deque in Python

Last Updated : 06 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Example:

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

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

Deque in Python

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.

Operations on deque 

Here’s a table listing built-in operations of a deque in Python with descriptions and their corresponding time complexities:

OperationDescriptionTime Complexity
append(x)Adds x to the right end of the deque.O(1)
appendleft(x)Adds x to the left end of the deque.O(1)
pop()Removes and returns an element from the right end of the deque.O(1)
popleft()Removes and returns an element from the left end of the deque.O(1)
extend(iterable)Adds all elements from iterable to the right end of the deque.O(k)
extendleft(iterable)Adds all elements from iterable to the left end of the deque (reversed order).O(k)
remove(value)Removes the first occurrence of value from the deque. Raises ValueError if not found.O(n)
rotate(n)Rotates the deque n steps to the right. If n is negative, rotates to the left.O(k)
clear()Removes all elements from the deque.O(n)
count(value)Counts the number of occurrences of value in the deque.O(n)
index(value)Returns the index of the first occurrence of value in the deque. Raises ValueError if not found.O(n)
reverse()Reverses the elements of the deque in place.O(n)

Appending and Deleting Dequeue Items

  • append(x): Adds x to the right end of the deque.
  • appendleft(x): Adds x to the left end of the deque.
  • extend(iterable): Adds all elements from the iterable to the right end.
  • extendleft(iterable): Adds all elements from the iterable to the left end (in reverse order).
  • remove(value): Removes the first occurrence of the specified value from the deque. If value is not found, it raises a ValueError.
  • pop(): Removes and returns an element from the right end.
  • popleft(): Removes and returns an element from the left end.
  • clear(): Removes all elements from the deque.
Python
from collections import deque  dq = deque([10, 20, 30])  # Add elements to the right dq.append(40)    # Add elements to the left dq.appendleft(5)    # extend(iterable) dq.extend([50, 60, 70])  print("After extend([50, 60, 70]):", dq)  # extendleft(iterable) dq.extendleft([0, 5])   print("After extendleft([0, 5]):", dq)  # remove method dq.remove(20) print("After remove(20):", dq)  # Remove elements from the right dq.pop()  # Remove elements from the left dq.popleft()    print("After pop and popleft:", dq)  # clear() - Removes all elements from the deque dq.clear()  # deque: [] print("After clear():", dq) 

Output:

After extend([50, 60, 70]): deque([5, 10, 20, 30, 40, 50, 60, 70])
After extendleft([0, 5]): deque([5, 0, 5, 10, 20, 30, 40, 50, 60, 70])
After remove(20): deque([5, 0, 5, 10, 30, 40, 50, 60, 70])
After pop and popleft: deque([0, 5, 10, 30, 40, 50, 60])
After clear(): deque([])

Accessing Item and length of deque

  • Indexing: Access elements by position using positive or negative indices.
  • len(): Returns the number of elements in the deque.
Python
import collections  dq = collections.deque([1, 2, 3, 3, 4, 2, 4])  # Accessing elements by index print(dq[0])   print(dq[-1])   # Finding the length of the deque print(len(dq))   

Output
1 4 7 

Count, Rotation and Reversal of a deque

  • count(value): This method counts the number of occurrences of a specific element in the deque.
  • rotate(n): This method rotates the deque by n steps. Positive n rotates to the right and negative n rotates to the left.
  • reverse(): This method reverses the order of elements in the deque.
Python
from collections import deque  # Create a deque dq = deque([10, 20, 30, 40, 50, 20, 30, 20])  # 1. Counting occurrences of a value print(dq.count(20))  # Occurrences of 20 print(dq.count(30))  # Occurrences of 30  # 2. Rotating the deque dq.rotate(2)  # Rotate the deque 2 steps to the right print(dq)  dq.rotate(-3)  # Rotate the deque 3 steps to the left print(dq)  # 3. Reversing the deque dq.reverse()  # Reverse the deque print(dq) 

Output
3 2 deque([30, 20, 10, 20, 30, 40, 50, 20]) deque([20, 30, 40, 50, 20, 30, 20, 10]) deque([10, 20, 30, 20, 50, 40, 30, 20]) 


Next Article
ChainMap in Python
author
kartik
Improve
Article Tags :
  • Python
  • deque
  • Python collections-module
  • Python-DSA
Practice Tags :
  • Deque
  • python

Similar Reads

  • Python Collections Module
    The collection Module in Python provides different types of containers. A Container is an object that is used to store different objects and provide a way to access the contained objects and iterate over them. Some of the built-in containers are Tuple, List, Dictionary, etc. In this article, we will
    13 min read
  • Namedtuple in Python
    Python supports a type of container dictionary called "namedtuple()" present in the module "collections". In this article, we are going to see how to Create a NameTuple and operations on NamedTuple. What is NamedTuple in Python?In Python, NamedTuple is present inside the collections module. It provi
    8 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
  • ChainMap in Python
    Python contains a container called "ChainMap" which encapsulates many dictionaries into one unit. ChainMap is member of module "collections". Example: # Python program to demonstrate # ChainMap from collections import ChainMap d1 = {'a': 1, 'b': 2} d2 = {'c': 3, 'd': 4} d3 = {'e': 5, 'f': 6} # Defin
    3 min read
  • Python | Counter Objects | elements()
    Counter class is a special type of object data-set provided with the collections module in Python3. Collections module provides the user with specialized container datatypes, thus, providing an alternative to Python's general-purpose built-ins like dictionaries, lists, and tuples. Counter is a sub-c
    6 min read
  • OrderedDict in Python
    An OrderedDict is a dictionary subclass that remembers the order in which keys were first inserted. The only difference between dict() and OrderedDict() lies in their handling of key order in Python. OrderedDict vs dict in PythonNote: Starting from Python 3.7, regular dictionaries (dict) also mainta
    10 min read
  • Defaultdict in Python
    In Python, defaultdict is a subclass of the built-in dict class from the collections module. It is used to provide a default value for a nonexistent key in the dictionary, eliminating the need for checking if the key exists before using it. Key Features of defaultdict:When we access a key that doesn
    6 min read
  • Collections.UserDict in Python
    An unordered collection of data values that are used to store data values like a map is known as Dictionary in Python. Unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized. Note: For mo
    2 min read
  • Collections.UserList in Python
    Python Lists are array-like data structure but unlike it can be homogeneous. A single list may contain DataTypes like Integers, Strings, as well as Objects. List in Python are ordered and have a definite count. The elements in a list are indexed according to a definite sequence and the indexing of a
    2 min read
  • Collections.UserString in Python
    Strings are the arrays of bytes representing Unicode characters. However, Python does not support the character data type. A character is a string of length one. Example: C/C++ Code # Python program to demonstrate # string # Creating a String # with single Quotes String1 = 'Welcome to the Geeks Worl
    2 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