
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Implement Queue in Python
When it is required to implement a queue using Python, a queue class is created, and methods to add and delete elements are defined. An instance of the class is created, and these methods are called using the instance and relevant output is displayed.
Below is a demonstration of the same −
Example
class Queue_struct: def __init__(self): self.items = [] def check_empty(self): return self.items == [] def enqueue_elem(self, data): self.items.append(data) def dequeue_elem(self): return self.items.pop(0) my_instance = Queue_struct() while True: print('Enqueue <value>') print('Dequeue') print('Quit') my_input = input('What operation would you perform ? ').split() operation = my_input[0].strip().lower() if operation == 'Enqueue': my_instance.enqueue_elem(int(my_input[1])) elif operation == 'Dequeue': if my_instance.check_empty(): print('The queue is empty...') else: print('The deleted value is : ', my_instance.dequeue_elem()) elif operation == 'Quit': break
Output
Enqueue <value> Dequeue Quit What operation would you perform ? Enqueue 45 Enqueue <value> Dequeue Quit What operation would you perform ? Enqueue 56 Enqueue <value> Dequeue Quit What operation would you perform ? Enqueue 89 Enqueue <value> Dequeue Quit What operation would you perform ? Dequeue Enqueue <value> Dequeue Quit What operation would you perform ? Dequeue Enqueue <value> Dequeue Quit What operation would you perform ? Quit
Explanation
The ‘Queue_struct’ class with required attributes is created.
It has an ‘init’ function that is used to create an empty list.
Another method named ‘check_empty’ that checks to see if a list is empty.
Another method named ‘enqueue_elem’ is defined that adds elements to the empty list.
A method named ‘dequeue_elem’ is defined, that deletes elements from the list.
An object of the ‘Queue_struct’ class is created.
The user input is taken for the operation that needs to be performed.
Depending on the user’ choice, the operation is performed.
Relevant output is displayed on the console.