Python Program to Implement a Circular Queue
Intermediate · Data structures
A circular queue is a queue stored in a fixed number of slots, where the end wraps around to the start, so slots freed at the front can be reused at the back. It keeps first-in, first-out order without ever shifting items along, and it is used for buffers in keyboards, printers and audio players. This program shows adding, removing, the wrap-around, and what happens when the queue is full or empty.
Program
Added 10 in slot 0 Added 20 in slot 1 Added 30 in slot 2 Added 40 in slot 3 Overflow: the queue is full, cannot add 50 Removed 10 Removed 20 Added 60 in slot 0 Added 70 in slot 1 Slots: [60, 70, 30, 40] | front is slot 2 Removed 30 Removed 40 Removed 60 Removed 70 Underflow: the queue is empty
How it works
- The queue lives in a list of fixed size,
slots, wherefrontis the slot of the first item andsizecounts the items, so the rear issizeslots after the front. - The
% self.capacityis what makes it circular: with 4 slots, one past slot 3 wraps round to slot 0 instead of running off the end. enqueue()refuses a new item whensizeequals the capacity (overflow), anddequeue()refuses whensizeis 0 (underflow).- After 10 and 20 are removed, 60 and 70 reuse slots 0 and 1, yet the items still come out in the order they went in: 30, 40, 60, 70.
- Nothing ever moves along the list, so adding and removing take the same short time however big the queue is.
Another way to write it
Using collections.deque with maxlen
Visited home -> recent: ['home'] Visited about -> recent: ['home', 'about'] Visited blog -> recent: ['home', 'about', 'blog'] Visited contact -> recent: ['about', 'blog', 'contact'] Visited shop -> recent: ['blog', 'contact', 'shop']
A deque with maxlen is a ready-made ring buffer, and when it is full, adding an item quietly drops the oldest one instead of reporting overflow, which suits a "last few items" list like recently visited pages.
Try it yourself
Add a peek() method that prints the front item without removing it, or a message when the queue is empty.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises