Getting the size of a queue in Python is easy. There are a few ways you can implement a queue in Python.
If you are using deque from the collections module, you can use the len() function to get the size of your queue.
from collections import deque
q = deque()
q.append(1)
q.append(2)
q.append(3)
print(len(q))
#Output:
3
If you are using Queue from the queue module, you should use the qsize() function to get the number of items in your queue.
from queue import Queue
q = Queue()
q.append(1)
q.append(2)
print(q.qsize())
#Output:
2
Queues are data structures which are simple, yet powerful, and can make our programming life easier depending on the requirements for our code.
When working with queues in Python, it can be valuable to be able to get the size and number of items in a queue.
There are a few different ways you can implement queues in Python. The collections module has deque which allows you to create a queue in your code. You can also use the queue module to create a queue.
Depending on which queue implementation you use, the way to get the size and length of your queue will be slightly different.
Getting the Length of deque Object in Python
If you are using deque from the collections module, you can use the len() function to get the size of your queue.
Below shows you a simple example of how to get the length of a deque variable with len() in Python.
from collections import deque
q = deque()
q.append(1)
q.append(2)
q.append(3)
print(len(q))
#Output:
3
Getting the Size of Queue in Python
If you are using Queue from the queue module, you should use the qsize() function to get the number of items in your queue.
Below shows you a simple example of how to get the length of a queue with qsize() in Python.
from queue import Queue
q = Queue()
q.append(1)
q.append(2)
print(q.qsize())
#Output:
2
Hopefully this article has been useful for you to learn how to find the size of a queue when using Python.