- This topic is empty.
-
AuthorPosts
-
February 14, 2026 at 6:06 am #6053
In Python, a Queue is a data structure that follows the rule:
FIFO — First-In, First-Out
This means the element that enters first is removed first.
To implement this, we first create a base class called
Container, and then extend it using aQueueclass.
✅ Step 1: Base Class —
Container📌 Context
The
Containerclass stores elements in a list.
It provides basic functionality:- Create an empty list
- Add elements
- Find the size of the list
It does not remove elements. That job is left to subclasses.
✅ Code:
ContainerClassclass Container: """ A container object stores elements in a list """ def __init__(self): """ Initializes an empty list """ self.myList = [] def size(self): """ Returns the number of elements in the list """ return len(self.myList) def add(self, elem): """ Adds an element to the end of the list """ self.myList.append(elem)
✅ Step 2: Subclass —
Queue📌 Context
The
Queueclass inherits fromContainer.It adds one new feature:
The ability to remove the oldest element.
Since
add()inserts elements at the end of the list, the oldest element is always at the front (index0).So,
remove()must delete from the front.
✅ Code:
QueueClassclass Queue(Container): """ A Queue follows FIFO (First-In, First-Out) """ def remove(self): """ Removes and returns the oldest element """ if self.size() == 0: return None # Queue is empty return self.myList.pop(0)
✅ Step 3: Using the Queue
📌 Context
Let’s see how this works in real use.
Elements are added in order and removed in the same order.
✅ Example Code
q = Queue() q.add("Apple") q.add("Banana") q.add("Cherry") print(q.remove()) # Apple print(q.remove()) # Banana print(q.remove()) # Cherry
✅ Output
Apple Banana Cherry
✅ Step 4: Why This Works (Logic)
Operation List State add(“Apple”) [“Apple”] add(“Banana”) [“Apple”, “Banana”] add(“Cherry”) [“Apple”, “Banana”, “Cherry”] remove() Removes “Apple” remove() Removes “Banana” append()→ adds to the endpop(0)→ removes from the front
This maintains FIFO ✔️
✅ Important Note (For Learners)
Using
pop(0)is fine for learning.But for very large queues, it is slow because Python must shift all elements.
In real projects, developers often use:
collections.dequeBut for basic understanding,
listis perfect.
🎯 Final Summary
Container→ stores dataQueue→ controls orderadd()→ end of listremove()→ front of list- Result → FIFO behavior
-
AuthorPosts
- You must be logged in to reply to this topic.

