EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Queue in Python

Home » Software Development » Software Development Tutorials » Python Tutorial » Queue in Python

Queue-in-Python

Introduction to Queue in Python

Queue are the containers for storing data items, that is waiting to be retrieved. One can control and manipulate data through queues. There are four types of queues:

  1. FIFO
  2. LIFO
  3. Priority Queue
  4. Circular Queue

There are two basic operations carried out in “Queue”:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

  • Enqueue is known as insertion.
  • Dequeue is known as deletion.

Queue-in-Python-img

Queue is open at both ends. The element which enters first is the one which comes out first from the queue. Random addition or deletion is not allowed in between queues. Queue helps you making the flow of tasks and keep a track of it.

General Queue Algorithm

Below are the points in the general queue algorithm:

1. Declare a list of elements and maximum size of the Queue

2. Set head and tail of queue to 0

3. Number of elements in the queue -> Size = Tail – Head

4. Enqueue operation:

  • Now check, if Size < MaxSize:
  • If yes: Append data to Queue and then increment Tail by 1
  • If it’s no, print message: Queue full

5. Dequeue operation

  • Check if Size > 0:
  • If yes: Pop the first element from the list and then increment Head by 1
  • If no: Call Reset method. Print message: Empty message

Python provides it in the form of module name “queue”, which can be imported to the python environment and used directly.

Examples to Implement Queue in Python

Below are examples mentioned:

Example #1. FIFO

Here is the example of FIFO queue: Addition and deletion of one element in the queue:

Popular Course in this category
Python Training Program (36 Courses, 13+ Projects)36 Online Courses | 13 Hands-on Projects | 189+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.8 (8,353 ratings)
Course Price

View Course

Related Courses
Programming Languages Training (41 Courses, 13+ Projects, 4 Quizzes)Angular JS Training Program (9 Courses, 7 Projects)

Code #1

import queue
s = queue.Queue()
type(s)

Output:

FIFO

FIFO is by default, if queue type is not defined explicitly. Now let’s put something in queue and see.

Code #2

import queue
s = queue.Queue()
type(s)
s.put(10)
s.get()

Output:

Queue in Python - 2

s.put() helps in keeping element inside queue. Whereas s.get() will help in retrieving element from the queue. Addition and deletion of multiple element in queue: Now since we added elements in queue, let’s see how it looks through the code below:

Code #3

import queue
s = queue.Queue()
for j in range(5):
s.put(j)
while not s.empty():
print(s.get())
print("ENDs")

Output:

Queue in Python - 3

Example #2. LIFO

Same addition and deletion can be done over LIFO as well. Here is the example of LIFO(last in first out) queue:

Code:

import queue
s = queue.LifoQueue()
for j in range(5):
s.put(j)
while not s.empty():
print(s.get())
print("ENDs")

Output:

LIFO

Example #3. Priority Queue

This queue is a bit different from LIFO and FIFO queue. Here order is not a matter of interest.

Code:

import queue
s = queue.PriorityQueue()
s.put(2)
s.put(0)
s.put(1)
while not s.empty():
print(s.get())
print("ENDs")

Output:

Priority Queue

So, as one can see the lowest value items come out of queue first. However, if there are two items holding the same value, then the order comes into consideration.

Example #4. Circular Queue

This is a type of queue, which is circular in shape. Here the end of the queue that is tail becomes the first of the queue that is head. This also works on the principle of “FIFO”. This is also called “Ring Buffer”. The application of the circular queue is mostly in the traffic system, CPU scheduling, etc.

Circular Queue Algorithm

Below we learn the algorithm circular queue

  • Initialize the queue with items. Set the size of the queue i.e. maxSize, Initialize values for head and tail pointers.

enqueue: Check, if the number of elements = maxSize – 1:

  • If Yes, then return message: Queue is full
  • If No, then add the new data element to the location of the tail pointer. Increment the tail pointer.

dequeue: Check if the number of elements in the queue = 0:

  • If Yes, then return message: Queue is empty
  • If No, Increment the head pointer.

size:

  • If, tail >= head, then size = tail – head
  • If, head > tail, then size = maxSize – (head-tail)

Operations in Queue

Now let’s see some operations related to queue:

1. Queue empty()

In returns True or False based on any item available in the queue. If the queue holds some values, it returns True. If the queue holds no items, it returns False.

Code:

import queue
s = queue.PriorityQueue()
s.put(2)
s.put(0)
s.put(1)
s.empty()

Output:

empty()

2. Queue full()

It returns True if the queue is full. Else False.

Code:

import queue
s = queue.PriorityQueue()
s.put(2)
s.put(0)
s.put(1)
s.full()

Output:

empty()

3. Queue task_done: If tasks is enqueued and going on. In order to check if it’s done, this function is used. It basically helps in thread-handling.

4. Qyeue qsize(): It returns the size of the queue.

Code:

import queue
s = queue.PriorityQueue()
s.put(2)
s.put(0)
s.put(1)
s.qsize()

Output:

full()

5. Queue put(): It puts an item in the queue.

6. Queue get():> This function get() is use to remove item from queue.

“Collections.deque” and “multiprocessing.queue” are two more good python module which can be explored for queues.

Example of Multiprocessing.Queue

This is a type of queue where items need to be processed in parallel mode. It tends to share data among processes.

Python Code

From multiprocessing import Queue

Code #1

qq = Queue()
qq.put('dance')
qq.put('play')
qq.put('read')
qq.put('sleep')
qq

Output:

Queue in Python - 8

Code #2

qq = Queue()
qq.put('dance')
qq.put('play')
qq.put('read')
qq.put('sleep')
qq.get()

Output:

Queue in Python - 9

Code #3

qq = Queue()
qq.put('dance')
qq.put('play')
qq.put('read')
qq.put('sleep')
qq.get()
qq.get()

Output:

Queue in Python - 10

Code #4

qq = Queue()
qq.put('dance')
qq.put('play')
qq.put('read')
qq.put('sleep')
qq.get()
qq.get()
qq.get()

Output:

Queue in Python - 11

Code #5

qq = Queue()
qq.put('dance')
qq.put('play')
qq.put('read')
qq.put('sleep')
qq.get()
qq.get()
qq.get()
qq.get()

Output:

Queue in Python - 12

Conclusion

The above covered is one of the most important concepts in data structures of python. We discussed the types of queues and its operations, which should help you get a good grip over it and moreover to understand its real use cases. Stacks and queue are the most widely used data structures in the real world. After a good understanding of this, one will feel confident to solve problems related to data storage inefficiencies effectively.

Recommended Articles

This is a guide to Queue in Python. Here we discuss an introduction to Queue in Python, algorithm circular, with respective examples for better understanding. You can also go through our other related articles to learn more –

  1. Python Power Function
  2. Python Unique List
  3. Python References
  4. Nested IF Statement in Python

All in One Software Development Bundle (600+ Courses, 50+ projects)

600+ Online Courses

50+ projects

3000+ Hours

Verifiable Certificates

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
Python Tutorial
  • Advanced
    • Scope in Python
    • Python Collections
    • Constructor in Python
    • Destructor in Python
    • Python Overloading
    • Overriding in Python
    • Function Overloading in Python
    • Method Overloading in Python
    • Operator Overloading in Python
    • Method Overriding in Python
    • Encapsulation in Python
    • Static Method in Python
    • Assert in Python
    • Python References
    • Python Virtualenv
    • Python mkdir
    • Logistic Regression in Python
    • Dictionary in Python
    • Regular Expression in Python
    • Python Import Module
    • Python OS Module
    • Python Sys Module
    • Python Generators
    • Abstract Class in Python
    • Python File Operations
    • Sequences in Python
    • Stack in Python
    • Queue in Python
    • Tuples in Python
    • Python Magic Method
    • Python Sets
    • Python Set Methods
    • Priority Queues in Python
    • Reverse Engineering with Python
    • String Formatting in Python
    • Python isinstance
    • String Length Python
    • Python Concurrency
    • Python List
    • Python Initialize List
    • Python Unique List
    • Python Sort List
    • Python Reverse List
    • Python Empty List
    • List Comprehensions Python
    • List Operations in Python
    • Python Database Connection
    • Python SQLite
    • Python SQLite Create Database
    • Send Mail in Python
    • Bash Scripting and Python
    • Violent Python Book
    • NLP in Python
    • Matplotlib In Python
    • Gray Hat Python: Security
    • Python Subprocess
    • Python Threading Timer
    • Python Threadpool
    • Python Statistics Module
    • How to Call a Function in Python?
    • Python Curl
    • JSON in Python
    • Python json.dumps
    • Python Turtle
    • Python Unit Test
    • pass Keyword in Python
    • Tokenization in Python
    • Random Module in Python
    • Python Multiprocessing
    • Python getattr
    • Collection Module in Python
    • Print Statement in Python
    • Python Countdown Timer
    • Python Context Manager
    • File Handling in Python
    • Python Event Handler
    • Python Print Table
    • Python Docstring
    • Python Dictionary Keys
    • Python Iterator Dictionary
    • Python Class Attributes
    • Python Dictionary Methods
    • Namedtuple Python
    • Namedtuple Python
    • Namedtuple Python
    • Python Class Constants
    • Python Validation
    • Python Switch Case
    • Python Rest Server
    • Python Yield vs Return
    • Python Pickle vs JSON
  • Basics Part I
    • Introduction To Python
    • What Is Python
    • Careers in Python
    • Advantages of Python
    • Uses of Python
    • Python Features
    • Python Fast And python psyco
    • Python ImportError
    • Benefits and Limitations of Using Python
    • What can I do with?Python
    • Is Python a scripting language
    • Is Python Object Oriented
    • Is Python Open Source
    • Python Socket Programming
    • Useful Tips on Python Programming
    • Python You Should Be Using It
    • Python Web Development
    • Python Programming Beginners Tutorails
    • Practical Python Programming for Non-Engineers
    • Python Programming for the Absolute Beginner
    • Versions of?Python
  • Basic Part II
    • Comments in Python
    • Finally in Python
    • Python Multiline Comment
    • Python Data Types
    • Python Variables
    • Python Variable Types
    • Python Global Variable
    • Python Variable Scope
    • Python Private Variables
    • Python Default Arguments
    • Python Command-line Arguments
    • Indentation in Python
    • Object in Python
    • Python Keywords
    • Python Literals
    • Pointers in Python
    • Iterators in Python
    • Python User Input
    • Python Enumerate
    • Python Commands
    • Type Casting in Python
    • Python Identifiers
    • Python Constants
    • What is NumPy in Python?
    • Cheat Sheet Python
  • Frameworks
    • Python Frameworks
    • Python Compilers
    • Python Editors
    • Best Compiler for Python
    • Python IDE for Windows
    • Python IDE on Linux
  • Installation
    • How To Install Python
    • Install Python on Linux
    • Install Python on Windows
    • Install Anaconda Python
  • Operator
    • Python Operators
    • Arithmetic Operators in Python
    • Python Comparison Operators
    • Logical Operators in Python
    • Assignment Operators in Python
    • Unary Operators in Python
    • String Operators in Python
    • Boolean Operators in Python
    • Identity Operators in Python
    • Python Bitwise Operator
    • Python Remainder Operator
    • Python Modulus Operator
  • Control Statement
    • Conditional Statements in Python
    • Control Statements in Python
    • If Condition in Python
    • If Statement in Python
    • If Else Statement in Python
    • else if Statement in Python
    • Nested IF Statement in Python
    • Break Statement in Python
    • Python Switch Statement
  • Loops
    • Loops in Python
    • For Loop in Python
    • While Loop in Python
    • Do While Loop in Python
    • Python Nested Loops
    • Python Infinite Loop
    • Python Event Loop
  • Sorting
    • Sorting in Python
    • Sorting Algorithms in Python
    • Bubble Sort in Python
    • Merge Sort in Python
    • Heap Sort in Python
    • Quick Sort in Python
    • Python Sorted Function
  • Function
    • Python Built-in Functions
    • Math Functions in Python
    • Python String Functions
    • Trigonometric Functions in Python
    • Python Input Function
    • Python Input String
    • Python String Operations
    • Python Stream
    • Python Multiline String
    • Python Regex
    • Python Regex Tester
    • Python regex replace
    • Python File Methods
    • Python Import CSV
    • Python Read CSV File
    • Python write CSV file
    • Python Delete File
    • Python File readline
    • Python if main
    • Python Main Method
    • List Method in Python
    • Python List Length
    • Recursive Function in Python
    • Copy List in Python
    • Python Range Function
    • Python Substring
    • Python list remove()
    • Python List Index
    • Python Set Function
    • Python len Function
    • Python eval()
    • Python Counter
    • ord Function in Python
    • strip Function in Python
    • Split Function in Python
    • Python Round Function
    • Python Map Function
    • Python String Join
    • Python format() Function
    • Python Contextlib
    • Python Compare Strings
    • Python Return Value
    • Python List count
    • Filter in Python
    • Python Slice String
    • Python Absolute Value
    • Python Trim String
    • Python Type Function
    • Lowercase in Python
    • Python xrange
    • Python yield
    • Python Find String
    • Max Function in Python
    • Python Power Function
    • pop() in Python
    • Python argparse
    • Python Pickle
    • Python Zip Function
    • Python Split String
    • super() in Python
    • Python Extend
    • Python String Replace
    • Python PEP8
    • Python Filter Function
    • Python if then else
    • Lambda in Python
    • Python BeautifulSoup
    • Python Sleep
    • Python Function Generator
    • Python @classmethod decorator
    • Python Endswith
    • Python BufferedReader
    • Python Async
    • Python Parser
    • Python SystemExit
    • Python pip
    • Python kwargs
  • Array
    • Arrays in Python
    • 2D Arrays In Python
    • 3d Arrays in Python
    • Multidimensional Array in Python
    • Python Array Functions
    • String Array in Python
    • Python Sort Array
    • Python Array Length
  • Inheritance
    • Inheritance in Python
    • Single Inheritance in Python
    • Multiple Inheritance in Python
    • Interface in Python
  • Exception
    • Python Exception Handling
    • Custom Exception in Python
    • Indentation Error in Python
    • Python IOError
    • Python EOFError
    • Python NotImplementedError
    • Python TypeError
    • Python ValueError
    • Python AssertionError
    • Python Unicode Error
    • Python NameError
    • Python StopIteration
    • Python OverflowError
    • Python KeyboardInterrupt
  • Tkinter
    • Tkinter Widgets
    • Python Tkinter Button
    • Python Tkinter Canvas
    • Tkinter Frame
    • Tkinter LabelFrame
    • Python Tkinter Label
    • Tkinter Scrollbar
    • Tkinter Listbox
    • Tkinter Spinbox
    • Tkinter Checkbutton
    • Tkinter Menu
    • Tkinter Menubutton
    • Tkinter OptionMenu
    • Tkinter Messagebox
    • Tkinter Grid
    • Python Tkinter Entry
    • Tkinter after
    • Tkinter Colors
    • Tkinter Font
    • Tkinter PhotoImage
    • Tkinter TreeView
    • Tkinter Notebook
    • Tkinter Bind
    • Tkinter Icon
    • Tkinter Window Size
    • Tkinter Color Chart
    • Tkinter Slider
    • Tkinter Calculator
  • Programs
    • Patterns in Python
    • Star Patterns in Python
    • Swapping in Python
    • Factorial in Python
    • Fibonacci Series in Python
    • Reverse Number in Python
    • Palindrome in Python
    • Random Number Generator in Python
    • Prime Numbers in Python
    • Armstrong Number in Python
    • Strong Number in Python
    • Leap Year Program in Python
    • Square Root in Python
    • Python Reverse String
    • Python Object to String
    • Python Object to JSON
    • Python Classmethod vs Staticmethod
  • Python 3
    • Python 3 Commands
    • Python 3 cheat sheet
  • Interview Question
    • Python Interview Questions And Answers

Related Courses

Python Certification Course

Programming Languages Courses

Angular JS Certification Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - Python Certification Course Learn More