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:
How to check if the PyMongo Cursor is Empty?
Next article icon

How to check if a deque is empty in Python?

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

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 elements from the front and end that’s why It is also called a double-ended queue.

It is necessary to check whether a data structure like linked list, deque, tree, etc. is empty or not before popping out the elements to make our code error-free. Because when we try to remove any element from an empty deque we get an Index Error. Let’s see it with an example.

Python3

# Import deque
from collections import deque
 
# Initialize an emppty deque
deque1 = deque()
 
# Removing an element from deque
deque1.pop()
                      
                       

Output:

Traceback (most recent call last):   File "/home/01a7ab0c685202c4f679846e50b77e8d.py", line 8, in <module>     deque1.pop() IndexError: pop from an empty deque

In the above code, we are importing a deque from the collections module and then initializing an empty deque. after that, we are trying to remove an element from an empty deque which results in an Index Error as seen in the output.

Time complexity: O(1)

Auxiliary space: O(1)

Let’s learn how to check whether the deque is empty or not.

Example 1:

Use len() function to find whether the deque is empty or not.

Python3

# import deque
from collections import deque
 
# create an empty deque
deque1 = deque()
 
if len(deque1) == 0:
    print("deque is Empty")
                      
                       

Output:

deque is Empty

In the above code, we are importing a deque using the collections module creating an empty deque after that checking whether the deque is empty or not using len() function which returns the length of the deque if the length of the deque is equal to “0” it will print “deque is empty”.

Time complexity: O(1) 

Auxiliary space: O(1)

Example 2:

Using the bool() method, we can check whether the deque is empty or not. The bool() method converts the deque into a Boolean and if the value is False it indicates the deque is empty.

Python3

# import deque
from collections import deque
 
# create an empty deque
deque1 = deque()
 
if bool(deque1) == False:
    print("deque is Empty")
                      
                       

Output:

deque is Empty

In this example, we are converting deque into a boolean explicitly if a deque has data it converts to True and if deque is empty it converts to False.

Time complexity: O(1)

Auxiliary space: O(1)

Example 3:

Python3

# Import deque
from collections import deque
# Initialize a list
deque1 = deque(["Geeks","for","Geeks"])
# Running a infinite loop
while(True):
     # Check if deque is empty or not
    if deque1:
        print(deque1)
        deque1.pop()
    else:
        print("Deque is empty")
        # Break the loop if deque
        # became empty
        break
                      
                       

Output:

deque(['Geeks', 'for', 'Geeks']) deque(['Geeks', 'for']) deque(['Geeks']) Deque is empty

In the above code, We are initializing a deque with some data in it and then running an infinite while loop. Inside a loop, we are checking whether the deque is empty or not in every iteration if the deque is not empty pop an item from the deque else print the message “Deque is empty” and break the loop. In this example, if statement implicitly converts the deque into a boolean if the deque is not empty it converts True and if the deque is empty it converts to False.

Time complexity: O(n)

Auxiliary space: O(1)



Next Article
How to check if the PyMongo Cursor is Empty?

A

akhilvasabhaktula03
Improve
Article Tags :
  • Python
Practice Tags :
  • python

Similar Reads

  • How to check if a csv file is empty in pandas
    Reading CSV (Comma-Separated Values) files is a common step in working with data, but what if the CSV file is empty? Python script errors and unusual behavior can result from trying to read an empty file. In this article, we'll look at methods for determining whether a CSV file is empty before attem
    4 min read
  • How To Check If Cell Is Empty In Pandas Dataframe
    An empty cell or missing value in the Pandas data frame is a cell that consists of no value, even a NaN or None. It is typically used to denote undefined or missing values in numerical arrays or DataFrames. Empty cells in a DataFrame can take several forms: NaN: Represents missing or undefined data.
    6 min read
  • How to check if the PyMongo Cursor is Empty?
    MongoDB is an open source NOSQL database, and is implemented in C++. It is a document oriented database implementation that stores data in structures called Collections (group of MongoDB documents). PyMongo is a famous open source library that is used for embedded MongoDB queries. PyMongo is widely
    2 min read
  • How to Check if PySpark DataFrame is empty?
    In this article, we are going to check if the Pyspark DataFrame or Dataset is Empty or Not. At first, let's create a dataframe [GFGTABS] Python3 # import modules from pyspark.sql import SparkSession from pyspark.sql.types import StructType, StructField, StringType # defining schema schema = StructTy
    1 min read
  • Check if a list is empty or not in Python
    In article we will explore the different ways to check if a list is empty with simple examples. The simplest way to check if a list is empty is by using Python's not operator. Using not operatorThe not operator is the simplest way to see if a list is empty. It returns True if the list is empty and F
    2 min read
  • How to Check a Column is Empty or Null in MySQL?
    In the databases, determining whether a column is empty or null is a common task. MySQL provides various techniques to perform this check, allowing users to filter and manipulate data efficiently. This article delves into the methods for checking if a column is empty or null in MySQL, outlining the
    4 min read
  • How to check dataframe is empty in Scala?
    In this article, we will learn how to check dataframe is empty or not in Scala. we can check if a DataFrame is empty by using the isEmpty method or by checking the count of rows. Syntax: val isEmpty = dataframe.isEmpty OR, val isEmpty = dataframe.count() == 0 Here's how you can do it: Example #1: us
    2 min read
  • Python - How to Check if a file or directory exists
    Sometimes it's necessary to verify whether a dictionary or file exists. This is because you might want to make sure the file is available before loading it, or you might want to prevent overwriting an already-existing file. In this tutorial, we will cover an important concept of file handling in Pyt
    5 min read
  • How to check if an object is iterable in Python?
    In simple words, any object that could be looped over is iterable. For instance, a list object is iterable and so is an str object. The list numbers and string names are iterables because we are able to loop over them (using a for-loop in this case). In this article, we are going to see how to check
    3 min read
  • How to check if a Python variable exists?
    Checking if a Python variable exists means determining whether a variable has been defined or is available in the current scope. For example, if you try to access a variable that hasn't been assigned a value, Python will raise a NameError. Let’s explore different methods to efficiently check if a va
    4 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