Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check deque length in Python

How to check a deque's length in python?

I don't see they provide deque.length in Python...

http://docs.python.org/tutorial/datastructures.html

from collections import deque queue = deque(["Eric", "John", "Michael"]) 

How to check the length of this deque?

and can we initialize like

queue = deque([])   #is this length 0 deque? 
like image 630
runcode Avatar asked Sep 22 '12 23:09

runcode


People also ask

How do I find the size of a queue?

queue::size() is used to check whether the size of the associated queue container. This function returns an unsigned int value, i.e the size of the queue container, or the number of elements present in a queue container. This function returns 0 if the queue is empty or having no elements in it.

What does deque () do in Python?

A double-ended queue, or deque, has the feature of adding and removing elements from either end. The Deque module is a part of collections library. It has the methods for adding and removing elements which can be invoked directly with arguments.

Is deque faster than list Python?

Of course, it can be done using lists, but with deques, you already have the interface for that, and it's much faster.

Does deque have peek?

The deque data structure from the collections module does not have a peek method, but similar results can be achieved by fetching the elements with square brackets.


2 Answers

len(queue) should give you the result, 3 in this case.

Specifically, len(object) function will call object.__len__ method [reference link]. And the object in this case is deque, which implements __len__ method (you can see it by dir(deque)).


queue= deque([])   #is this length 0 queue? 

Yes it will be 0 for empty deque.

like image 187
K Z Avatar answered Oct 18 '22 10:10

K Z


it is simple just use .qsize() example:

a=Queue() a.put("abcdef") print a.qsize() #prints 1 which is the size of queue 

The above snippet applies for Queue() class of python. Thanks @rayryeng for the update.

for deque from collections we can use len() as stated here by K Z.

like image 29
Mani Avatar answered Oct 18 '22 12:10

Mani