How to check deque length in Python

PythonPython 3.xPython 2.7Data Structures

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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.

Solution 3 - Python

Yes we can check the length of queue object created from collections.

from collections import deque
class Queue():
    def __init__(self,batchSize=32):
        #self.batchSie = batchSize
        self._queue = deque(maxlen=batchSize)
        
    def enqueue(self, items):
        ''' Appending the items to the queue'''
        self._queue.append(items)
    
    def dequeue(self):
        '''remoe the items from the top if the queue becomes full '''
        return self._queue.popleft()

Creating an object of class

q = Queue(batchSize=64)
q.enqueue([1,2])
q.enqueue([2,3])
q.enqueue([1,4])
q.enqueue([1,22])

Now retrieving the length of the queue

#check the len of queue
print(len(q._queue)) 
#you can print the content of the queue
print(q._queue)
#Can check the content of the queue
print(q.dequeue())
#Check the length of retrieved item 
print(len(q.dequeue()))

check the results in attached screen shot

enter image description here

Hope this helps...

Solution 4 - Python

Use queue.rear+1 to get the length of the queue

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionruncodeView Question on Stackoverflow
Solution 1 - PythonK ZView Answer on Stackoverflow
Solution 2 - PythonManiView Answer on Stackoverflow
Solution 3 - PythonVaibhav KView Answer on Stackoverflow
Solution 4 - PythonAvinash PrabhakarView Answer on Stackoverflow