[Solved] How to check if a deque is empty in Python?

How to check if a deque is empty in Python?

Solution #1:

If d is your deque, use

if d:
    # not empty
else:
    # empty

This will implicitly convert d to a bool, which yields True if the deque contains any items and False if it is empty.

Respondent: Sven Marnach

Solution #2:

There are two main ways:

1) Containers can be used as booleans (with false indicating the container is empty):

2) Containers in Python also have a __len__ method to indicate their size.

Here are a few patterns:

   non_empty = bool(d)           # Coerce to a boolean value  

   empty = not d                 # Invert the boolean value  

   if d:                         # Test the boolean value 
       print('non-empty')

   while d:                      # Loop until empty
       x = d.pop()
       process(x)

   if len(d) == 0:               # Test the size directly  
      print('empty')

The latter technique isn’t as fast or succinct as the others, but it does have the virtue of being explicit for readers who may not know about the boolean value of containers.

Other ways are possible. For example, indexing with d[0] raises an IndexError for an empty sequence. I’ve seen this used a few times.

Hope this helps 🙂

Respondent: Raymond Hettinger

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.