Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a deque is empty

Tags:

python

Is try-catch the only method to do that?

like image 664
Ilya Smagin Avatar asked Apr 13 '11 16:04

Ilya Smagin


People also ask

What is the condition to check for deque is empty?

isEmpty() method in Java is used to check and verify if an ArrayDeque is empty or not. It returns True if the Deque is empty else it returns False.

Is deque empty Python?

To check if a deque variable is empty in Python, you can check if the deque has length 0. You can also convert it to a boolean and check if the deque converted to a boolean is False. The deque object from the collections module gives us a data structure which is a double-ended queue.

How do you find the length of a deque?

Use the len() function to get the length of a deque object.


2 Answers

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.

like image 117
Sven Marnach Avatar answered Sep 25 '22 10:09

Sven Marnach


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.

like image 39
Raymond Hettinger Avatar answered Sep 23 '22 10:09

Raymond Hettinger