Code Explanation:
๐น 1. Importing Queue
from queue import Queue
✅ Explanation
Queue is imported from Python's built-in queue module.
A Queue follows the FIFO (First In, First Out) principle.
This means the first element inserted is the first element removed.
Think of a queue like people standing in a line.
Queue
↓
Person A
Person B
Person C
↓
Exit Order
A
B
C
Nothing executes yet.
๐น 2. Creating a Queue Object
q = Queue()
✅ Explanation
A new empty Queue object is created.
Current Memory
q
↓
Queue
↓
Empty
The queue currently contains no elements.
Front
↓
[]
↑
Rear
๐น 3. Inserting the First Element
q.put(10)
✅ Explanation
The put() method inserts an element at the rear (end) of the queue.
Before:
Queue
↓
[]
After:
Front
↓
10
↑
Rear
Current Queue
[10]
๐น 4. Inserting the Second Element
q.put(20)
✅ Explanation
Again, put() inserts the new element at the rear.
Before:
Front
↓
10
After:
Front
↓
10
20
↑
Rear
Current Queue
[10, 20]
Notice:
10 entered first
20 entered second
๐น 5. Removing the First Element
print(q.get())
✅ Explanation
The get() method removes and returns the front element.
Current Queue
Front
↓
10
20
Python removes:
10
Remaining Queue
Front
↓
20
Python prints
10
๐น 6. Removing the Second Element
print(q.get())
✅ Explanation
Again, get() removes the front element.
Current Queue
Front
↓
20
Python removes:
20
Queue becomes empty.
[]
Python prints
20
๐ฏ Final Output
10
20

0 Comments:
Post a Comment