Queue in Python

Last Updated : 09 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Like a stack, the queue is a linear data structure that stores items in a First In First Out (FIFO) manner. With a queue, the least recently added item is removed first. A good example of a queue is any queue of consumers for a resource where the consumer that came first is served first.
 

Queue in Python


Operations associated with queue are: 

  • Enqueue: Adds an item to the queue. If the queue is full, then it is said to be an Overflow condition – Time Complexity : O(1)
  • Dequeue: Removes an item from the queue. The items are popped in the same order in which they are pushed. If the queue is empty, then it is said to be an Underflow condition – Time Complexity : O(1)
  • Front: Get the front item from queue – Time Complexity : O(1)
  • Rear: Get the last item from queue – Time Complexity : O(1)

Implement a Queue in Python

There are various ways to implement a queue in Python. This article covers the implementation of queue using data structures and modules from Python library. Python Queue can be implemented by the following ways:

Implementation using list

List is a Python’s built-in data structure that can be used as a queue. Instead of enqueue() and dequeue(), append() and pop() function is used. However, lists are quite slow for this purpose because inserting or deleting an element at the beginning requires shifting all of the other elements by one, requiring O(n) time.
The code simulates a queue using a Python list. It adds elements ‘a’, ‘b’, and ‘c’ to the queue and then dequeues them, resulting in an empty queue at the end. The output shows the initial queue, elements dequeued (‘a’, ‘b’, ‘c’), and the queue’s empty state.

Python
queue = []
queue.append('a')
queue.append('b')
queue.append('c')
print("Initial queue")
print(queue)
print("\nElements dequeued from queue")
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))
print("\nQueue after removing elements")
print(queue)

Output: 

Initial queue
['a', 'b', 'c']
Elements dequeued from queue
a
b
c
Queue after removing elements
[]


Implementation using collections.deque

Queue in Python can be implemented using deque class from the collections module. Deque is preferred over list in the cases where we need quicker append and pop operations from both the ends of container, as deque provides an O(1) time complexity for append and pop operations as compared to list which provides O(n) time complexity. Instead of enqueue and deque, append() and popleft() functions are used.
The code uses a deque from the collections module to represent a queue. It appends ‘a’, ‘b’, and ‘c’ to the queue and dequeues them with q.popleft(), resulting in an empty queue. Uncommenting q.popleft() after the queue is empty would raise an IndexError. The code demonstrates queue operations and handles an empty queue scenario.

Python
from collections import deque
q = deque()
q.append('a')
q.append('b')
q.append('c')
print("Initial queue")
print(q)
print("\nElements dequeued from the queue")
print(q.popleft())
print(q.popleft())
print(q.popleft())

print("\nQueue after removing elements")
print(q)

Output: 
 

Initial queue
deque(['a', 'b', 'c'])
Elements dequeued from the queue
a
b
c
Queue after removing elements
deque([])

Implementation using queue.Queue

Queue is built-in module of Python which is used to implement a queue. queue.Queue(maxsize) initializes a variable to a maximum size of maxsize. A maxsize of zero ‘0’ means a infinite queue. This Queue follows FIFO rule. 
There are various functions available in this module: 

  • maxsize – Number of items allowed in the queue.
  • empty() – Return True if the queue is empty, False otherwise.
  • full() – Return True if there are maxsize items in the queue. If the queue was initialized with maxsize=0 (the default), then full() never returns True.
  • get() – Remove and return an item from the queue. If queue is empty, wait until an item is available.
  • get_nowait() – Return an item if one is immediately available, else raise QueueEmpty.
  • put(item) – Put an item into the queue. If the queue is full, wait until a free slot is available before adding the item.
  • put_nowait(item) – Put an item into the queue without blocking. If no free slot is immediately available, raise QueueFull.
  • qsize() – Return the number of items in the queue.

Example: This code utilizes the Queue class from the queue module. It starts with an empty queue and fills it with ‘a’, ‘b’, and ‘c’. After dequeuing, the queue becomes empty, and ‘1’ is added. Despite being empty earlier, it remains full, as the maximum size is set to 3. The code demonstrates queue operations, including checking for fullness and emptiness.

Python
from queue import Queue
q = Queue(maxsize = 3)
print(q.qsize()) 
q.put('a')
q.put('b')
q.put('c')
print("\nFull: ", q.full()) 
print("\nElements dequeued from the queue")
print(q.get())
print(q.get())
print(q.get())
print("\nEmpty: ", q.empty())
q.put(1)
print("\nEmpty: ", q.empty()) 
print("Full: ", q.full())

Output: 
 

0
Full: True
Elements dequeued from the queue
a
b
c
Empty: True
Empty: False
Full: False

Queue in Python – FAQs

What is a queue in Python? 

In Python, a queue is a linear data structure that follows the First-In-First-Out (FIFO) principle. It operates like a real-world queue or line at a ticket counter, where the first person to join the queue is the first to be served.

Is the queue FIFO or LIFO?

A queue in Python, as well as in most programming languages, is FIFO (First-In-First-Out). This means that the element that is added first is the first one to be removed.

What is front and rear queue in Python?

  • Front: The front of the queue refers to the position where elements are removed (dequeued).
  • Rear: The rear (or back) of the queue refers to the position where new elements are added (enqueued).

What is the difference between front and rear in queue?

The main difference between the front and rear of a queue lies in their roles:

  • Front: This is where elements are dequeued or removed from the queue.
  • Rear: This is where elements are enqueued or added to the queue.

Together, they define the boundaries of the queue structure, with elements flowing from the rear to the front.

What is the difference between queue and lock in Python?

  • Queue: A queue in Python (like queue.Queue from the queue module) is a data structure used for managing elements in a FIFO manner, typically used for communication between threads or processes.
  • Lock: A lock (like threading.Lock from the threading module) is a synchronization mechanism used to prevent multiple threads from simultaneously accessing shared resources. It ensures that only one thread can execute a critical section of code at a time.


What is the difference between queue and stack in Python?

A queue is FIFO (First-In-First-Out), while a stack is LIFO (Last-In-First-Out). Queues prioritize oldest elements for removal, whereas stacks prioritize newest.



Previous Article
Next Article

Similar Reads

Stack and Queue in Python using queue Module
A simple python List can act as queue and stack as well. Queue mechanism is used widely and for many purposes in daily life. A queue follows FIFO rule(First In First Out) and is used in programming for sorting and for many more things. Python provides Class queue as a module which has to be generally created in languages such as C/C++ and Java. 1.
3 min read
Priority Queue using Queue and Heapdict module in Python
Priority Queue is an extension of the queue with the following properties. An element with high priority is dequeued before an element with low priority. If two elements have the same priority, they are served according to their order in the queue. queue.PriorityQueue(maxsize) It is a constructor for a priority queue. maxsize is the number of eleme
3 min read
Difference between queue.queue vs collections.deque in Python
Both queue.queue and collections.deque commands give an idea about queues in general to the reader but, both have a very different application hence shouldn't be confused as one. Although they are different and used for very different purposes they are in a way linked to each other in terms of complete functionality. Before we jump into what they a
3 min read
Python multiprocessing.Queue vs multiprocessing.manager().Queue()
In Python, the multiprocessing module allows for the creation of separate processes that can run concurrently on different cores of a computer. One of the ways to communicate between these processes is by using queues. The multiprocessing module provides two types of queues: The Queue class is a simple way to create a queue that can be used by mult
10 min read
Heap queue (or heapq) in Python
Heap data structure is mainly used to represent a priority queue. In Python, it is available using the "heapq" module. The property of this data structure in Python is that each time the smallest heap element is popped(min-heap). Whenever elements are pushed or popped, heap structure is maintained. The heap[0] element also returns the smallest elem
7 min read
Priority Queue in Python
Priority Queues are abstract data structures where each data/value in the queue has a certain priority. For example, In airlines, baggage with the title “Business” or “First-class” arrives earlier than the rest. Priority Queue is an extension of the queue with the following properties. An element with high priority is dequeued before an element wit
2 min read
Python | Queue using Doubly Linked List
A Queue is a collection of objects that are inserted and removed using First in First out Principle(FIFO). Insertion is done at the back(Rear) of the Queue and elements are accessed and deleted from first(Front) location in the queue. Queue Operations:1. enqueue() : Adds element to the back of Queue. 2. dequeue() : Removes and returns the first ele
3 min read
Multithreaded Priority Queue in Python
The Queue module is primarily used to manage to process large amounts of data on multiple threads. It supports the creation of a new queue object that can take a distinct number of items. The get() and put() methods are used to add or remove items from a queue respectively. Below is the list of operations that are used to manage Queue: get(): It is
2 min read
Heap and Priority Queue using heapq module in Python
Heaps are widely used tree-like data structures in which the parent nodes satisfy any one of the criteria given below. The value of the parent node in each level is less than or equal to its children's values - min-heap.The value of the parent node in each level higher than or equal to its children's values - max-heap. The heaps are complete binary
5 min read
Dumping queue into list or array in Python
Prerequisite: Queue in Python Here given a queue and our task is to dump the queue into list or array. We are to see two methods to achieve the objective of our solution. Example 1: In this example, we will create a queue using the collection package and then cast it into the list C/C++ Code # Python program to # demonstrate queue implementation #
2 min read
Circular Queue in Python
A Circular Queue is a kind of queue that can insert elements inside it dynamically. Suppose, in a given array there is not any space left at the rare but we have space at the front in the normal queue it is not possible to insert elements at the front but in the case of a circular queue we can do that. So in this case, once the array is full till t
3 min read
How to Fix 'Waiting in Queue' Error in Python
In Python, handling and managing queues efficiently is crucial especially when dealing with concurrent or parallel tasks. Sometimes, developers encounter a 'Waiting in Queue' error indicating that a process or thread is stuck waiting for the resource or a task to complete. This error can stem from several issues including deadlocks, insufficient re
3 min read
Python - Queue.LIFOQueue vs Collections.Deque
Both LIFOQueue and Deque can be used using in-built modules Queue and Collections in Python, both of them are data structures and are widely used, but for different purposes. In this article, we will consider the difference between both Queue.LIFOQueue and Collections.Deque concerning usability, execution time, working, implementation, etc. in Pyth
3 min read
PYGLET – Adding Media in Queue of Player
In this article, we will see how we can add media in queue of player of PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia, etc. A window is a "heavyweight" object occupying operating system resources. Windows may appear as floating regions or can be set to fill a
3 min read
Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Python program to build flashcard using class in Python
In this article, we will see how to build a flashcard using class in python. A flashcard is a card having information on both sides, which can be used as an aid in memoization. Flashcards usually have a question on one side and an answer on the other. Particularly in this article, we are going to create flashcards that will be having a word and its
2 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
2 min read
Python | Add Logging to Python Libraries
In this article, we will learn how to add a logging capability to a library, but don’t want it to interfere with programs that don’t use logging. For libraries that want to perform logging, create a dedicated logger object, and initially configure it as shown in the code below - Code #1 : C/C++ Code # abc.py import logging log = logging.getLogger(_
2 min read
JavaScript vs Python : Can Python Overtop JavaScript by 2020?
This is the Clash of the Titans!! And no...I am not talking about the Hollywood movie (don’t bother watching it...it's horrible!). I am talking about JavaScript and Python, two of the most popular programming languages in existence today. JavaScript is currently the most commonly used programming language (and has been for quite some time!) but now
5 min read
Python | Index of Non-Zero elements in Python list
Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming. Let's discuss a shorthand by which we can perform this particular task. Method : Using enumerate() + list comprehension This method can be
6 min read
MySQL-Connector-Python module in Python
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command. In this article, we will be disc
2 min read
Python - Read blob object in python using wand library
BLOB stands for Binary Large OBject. A blob is a data type that can store binary data. This is different than most other data types used in databases, such as integers, floating point numbers, characters, and strings, which store letters and numbers. BLOB is a large complex collection of binary data which is stored in Database. Basically BLOB is us
2 min read
twitter-text-python (ttp) module - Python
twitter-text-python is a Tweet parser and formatter for Python. Amongst many things, the tasks that can be performed by this module are : reply : The username of the handle to which the tweet is being replied to. users : All the usernames mentioned in the tweet. tags : All the hashtags mentioned in the tweet. urls : All the URLs mentioned in the tw
3 min read
Reusable piece of python functionality for wrapping arbitrary blocks of code : Python Context Managers
Context Managers are the tools for wrapping around arbitrary (free-form) blocks of code. One of the primary reasons to use a context manager is resource cleanliness. Context Manager ensures that the process performs steadily upon entering and on exit, it releases the resource. Even when the wrapped code raises an exception, the context manager guar
7 min read
Creating and updating PowerPoint Presentations in Python using python - pptx
python-pptx is library used to create/edit a PowerPoint (.pptx) files. This won't work on MS office 2003 and previous versions. We can add shapes, paragraphs, texts and slides and much more thing using this library. Installation: Open the command prompt on your system and write given below command: pip install python-pptx Let's see some of its usag
4 min read
Python Debugger – Python pdb
Debugging in Python is facilitated by pdb module (python debugger) which comes built-in to the Python standard library. It is actually defined as the class Pdb which internally makes use of bdb(basic debugger functions) and cmd (support for line-oriented command interpreters) modules. The major advantage of pdb is it runs purely in the command line
5 min read
Filter Python list by Predicate in Python
In this article, we will discuss how to filter a python list by using predicate. Filter function is used to filter the elements in the given list of elements with the help of a predicate. A predicate is a function that always returns True or False by performing some condition operations in a filter method Syntax: filter(predicate, list) where, list
2 min read
Python: Iterating With Python Lambda
In Python, the lambda function is an anonymous function. This one expression is evaluated and returned. Thus, We can use lambda functions as a function object. In this article, we will learn how to iterate with lambda in python. Syntax: lambda variable : expression Where, variable is used in the expressionexpression can be an mathematical expressio
2 min read
Top 10 Python Built-In Decorators That Optimize Python Code Significantly
Python is a widely used high-level, general-purpose programming language. The language offers many benefits to developers, making it a popular choice for a wide range of applications including web development, backend development, machine learning applications, and all cutting-edge software technology, and is preferred for both beginners as well as
12 min read
Article Tags :
Practice Tags :