Get the length of a Queue in Python

avatar

Borislav Hadzhiev

Last updated: Jun 14, 2022

banner

Photo from Unsplash

Get the length of a Queue in Python #

To get the length of a queue in Python:

  1. Use the len() function to get the length of a deque object.
  2. Use the qsize() method to get the length of a queue object.
main.py
from collections import deque import queue deq = deque(['a', 'b', 'c']) # ✅ get length of deque object print(len(deq)) # 👉️ 3 q = queue.Queue() for item in range(15): q.put(item) # ✅ get length of queue object print('size of queue: ', q.qsize()) # 👉️ 15

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

The len() function returns the length (the number of items) of an object.

main.py
from collections import deque deq = deque(['a', 'b', 'c', 'd']) # 👇️ get length of deque object print(len(deq)) # 👉️ 4

The argument the function takes may be a sequence (a string, tuple, list, range or bytes) or a collection (a dictionary, set, or frozen set).

The len() function is always guaranteed to return the correct length of the deque object, regardless if you add or remove items.

main.py
from collections import deque deq = deque(['a', 'b']) deq.append('c') deq.append('d') print(len(deq)) # 👉️ 4 deq.remove('d') print(len(deq)) # 👉️ 3

If you use the queue module, use the qsize() method to get the length of the queue.

main.py
import queue q = queue.Queue() for item in range(15): q.put(item) # 👇️ get length of queue object print('size of queue: ', q.qsize()) # 👉️ 15 # 👇️ check if queue is empty print(q.empty()) # 👉️ False

The Queue.qsize method returns the approximate size of the queue.

You can use the Queue.empty method to check if the queue is empty.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.