Queue and Deque
A Queue in Python
With a Python list, the book keeps the front at index 0 and the rear at the end. Enqueue is myQueue.append(element); dequeue is myQueue.pop(0), which removes and returns the first element; peek returns myQueue[0] without removing it; isEmpty tests len(myQueue) == 0 and size returns len(myQueue). As with a stack, dequeue and peek must check isEmpty first.
A short trace — this prints [20, 30, 15], because the element dequeued from the front is 10 and 10 + 5 joins at the rear:q = []q.append(10)q.append(20)q.append(30)x = q.pop(0)q.append(x + 5)print(q)
pop() removes the last element (LIFO) and pop(0) removes the first (FIFO). Code-output questions hinge on which one is written, so read the brackets before tracing.With a Python list, the book keeps the front at index 0 and the rear at the end. Enqueue is myQueue.append(element); dequeue is myQueue.pop(0), which removes and returns the first element…
The Deque: a Double-Ended Queue
A deque (pronounced "deck", short for double-ended queue) is an ordered linear list in which elements can be added and removed at both ends. It therefore generalises both earlier structures: used with insertion and deletion at the same end it behaves as a stack, and with insertion at one end and deletion at the other it behaves as a queue. Its operations are insertFront, insertRear, deletionFront and deletionRear, with getFront and getRear to read either end. With a Python list: insertFront is insert(0, x), insertRear is append(x), deletionFront is pop(0) and deletionRear is pop().
Tracing a deque — after these lines the list is ['D', 'A', 'C']:d = []d.append("A")d.insert(0, "B")d.append("C")d.pop(0)d.insert(0, "D")
Step by step: [A] → [B, A] → [B, A, C] → [A, C] (B removed from the front) → [D, A, C].
Checking a palindrome with a deque. Insert every character of the word at the rear. Then, while more than one character remains, remove one from the front and one from the rear and compare them; any mismatch means the word is not a palindrome. "madam" and "level" pass; "lever" fails at the first comparison, l against r. Other uses the book names include letting a person who briefly left a queue rejoin at its front, and keeping a limited browsing history or undo list, where the oldest entry is dropped from one end as new ones arrive at the other.
- Insert and delete at the same end
- Behaves as a stack
- Insert at one end, delete at the other
- Behaves as a queue
- Insert every character at the rear
- Remove one from front, one from rear
- Compare the two charactersAny mismatch: not a palindrome
- Repeat while more than one remains"madam" passes; "lever" fails
A deque (pronounced "deck", short for double-ended queue) is an ordered linear list in which elements can be added and removed at both ends. It therefore generalises both earlier…
Worked Traces: Queue, Deque and a Real Use
A queue built on a Python list adds at the rear with append and removes from the front with pop(0). Start with q = [], then q.append(10), q.append(20) and q.append(30), so the queue is [10, 20, 30]. The call q.pop(0) returns 10, the element that arrived first, leaving [20, 30]. Compare the stack: pop() on the same list would have returned 30. A deque from collections allows both ends: from d = deque([1, 2, 3]), d.appendleft(0) gives [0, 1, 2, 3], d.append(4) gives [0, 1, 2, 3, 4], d.pop() returns 4 and d.popleft() returns 0, leaving [1, 2, 3].
Queues model any first-come, first-served system. A printer keeps jobs in a queue so that the document sent first prints first. A time-sharing computer gives each waiting process a turn in order, a method called round robin: a process that has not finished goes to the rear. A deque suits situations that need both ends, such as a palindrome checker that compares the front and rear characters while removing them, or a browser's history where recent pages are added at one end and old ones dropped from the other. A priority queue is different: it serves the most urgent item first, not the oldest, so it is not FIFO.
| Operation | Result | Structure after |
|---|---|---|
| q.append(30) | adds at rear | [10, 20, 30] |
| q.pop(0) | returns 10 | [20, 30] |
| d.appendleft(0) | adds at front | deque([0, 1, 2, 3]) |
| d.pop() | returns 4 | deque([0, 1, 2, 3]) |
| d.popleft() | returns 0 | deque([1, 2, 3]) |
A queue built on a Python list adds at the rear with append and removes from the front with pop(0). Start with q = [], then q.append(10), q.append(20) and q.append(30), so the queue is [10…
Circular Queues and Bounded Buffers
A simple list-based queue wastes space because dequeued positions at the front are never reused in a fixed-size array. A circular queue fixes this by letting the rear index wrap round to the start: after position n − 1 the next position is 0, computed as (rear + 1) % n. The queue is empty when front equals rear with no elements and full when (rear + 1) % n equals front, so one slot is usually sacrificed to tell the two states apart. This arrangement is used wherever data flows steadily between a producer and a consumer, such as a keyboard buffer or a stream of packets: the producer enqueues at the rear and the consumer dequeues from the front, and the wrap-around means memory is reused. For n = 5 and rear at index 4, one more enqueue goes to index 0, provided the queue is not full.
A simple list-based queue wastes space because dequeued positions at the front are never reused in a fixed-size array. A circular queue fixes this by letting the rear index wrap round to…
Key takeaways
- A queue adds at the REAR and removes from the FRONT, so it is FIFO; the operations are ENQUEUE and DEQUEUE.
- Dequeuing an empty queue is underflow; enqueuing a full fixed-size queue is overflow.
- With a Python list, enqueue is append(x), dequeue is pop(0), and the front is myQueue[0].
- Queues model print jobs, web-server requests and job scheduling — anything served in order of arrival.
- A deque allows insertion and deletion at both ends: same end gives a stack, opposite ends a queue.
- A palindrome is checked by filling a deque and comparing characters removed from the front and the rear.
Practice questions (24)
Attempt each one before opening the answer. Every explanation names the tempting wrong option as well as the right one, because that is where marks are lost.
What is the output of the following code?
q = []q.append(10)q.append(20)q.append(30)x = q.pop(0)q.append(x + 5)print(q)Show answer
Answer: B — `[20, 30, 15]`
pop(0) removes the element at the front, 10, so the list becomes [20, 30]; 10 + 5 = 15 is then appended at the rear, giving [20, 30, 15]. [10, 20, 35] treats pop(0) as pop(), removing 30 from the rear as a stack would. [15, 20, 30] puts the new element at the front, and [20, 30, 35] adds 5 to the wrong element.Which statement correctly describes a queue?
Show answer
Answer: D — Elements are added at the rear and removed from the front
A queue uses two ends — new elements join at the rear and the oldest leaves from the front — which is what makes it first in, first out. Adding and removing at a single top describes a stack. Removal at any position would make it an ordinary list, and removal by value describes a priority ordering, not the arrival order a queue keeps.A list d is used as a deque. What does print(d) show after these statements?
d = []d.append("A")d.insert(0, "B")d.append("C")d.pop(0)d.insert(0, "D")Show answer
Answer: B — `['D', 'A', 'C']`
Trace it: [A], then B inserted at the front gives [B, A], C appended gives [B, A, C], pop(0) removes B from the front leaving [A, C], and D inserted at the front gives [D, A, C]. The answer ending in B and A treats pop(0) as removing C from the rear. Putting D at the end confuses insert(0, x), which adds at the front, with append, which adds at the rear.
Show the other 21 questions
Starting with an empty queue, 4, 7 and 2 are enqueued in that order; then one dequeue is done, 9 is enqueued, and another dequeue is done. Which element is now at the front?
Show answer
Answer: C — 2
The queue is [4, 7, 2]; the first dequeue removes 4, giving [7, 2]; 9 joins at the rear, [7, 2, 9]; the second dequeue removes 7, leaving [2, 9], so 2 is at the front. 9 is the rear, the answer if the queue is mistaken for a stack. 7 is the front before the second dequeue, and 4 left the queue first of all.Several users send documents to one shared printer, and the documents must be printed in the order they were sent. Which data structure fits this best?
Show answer
Answer: A — Queue
Printing in the order of arrival is first in, first out, which is exactly a queue: each new job joins at the rear and the printer takes the job at the front. A stack would print the most recently sent document first, so whoever sent first would wait longest. Ordering by size or by name ignores the arrival order the question demands.A deque is used so that every insertion and every deletion happens at the front end only. How does it then behave?
Show answer
Answer: C — As a stack, because the last element inserted is the first removed
When additions and removals share one end, the element added last is always the one removed next — LIFO, a stack, whichever end is chosen. The queue option fixes on the word "front", but a queue needs insertion at the opposite end. A deque permits both ends without requiring both, and nothing in it keeps elements sorted.Assertion (A): When a Python list implements a queue as in the textbook, dequeue is written as myQueue.pop(0). Reason (R): The front of the queue is kept at index 0 of the list.
Show answer
Answer: A — Both A and R are true, and R is the correct explanation of A
Enqueue appends at the end of the list, so the rear is the end and the front — the oldest element — sits at index 0; dequeue must remove from there, which pop(0) does. R is therefore the very reason A is written that way. Calling R "not the explanation" misses that the choice of index 0 for the front is what decides which pop is used.What does the following code print?
def is_pal(word):dq = []for ch in word:dq.append(ch)while len(dq) > 1:if dq.pop(0) != dq.pop():return Falsereturn Trueprint(is_pal("level"), is_pal("lever"))Show answer
Answer: D — True False
For "level", the front and rear pairs are l–l and then e–e, and the single middle v ends the loop, so True. For "lever", the first pair removed is l from the front and r from the rear; they differ and the function returns False at once. True True would follow only if the comparison ignored the last letter, and the reversed pair confuses which word reads the same both ways.A queue works on the principle of:
Show answer
Answer: A — First In First Out (FIFO)
The element inserted first is removed first. LIFO describes a stack, the usual mix-up.In a queue, insertion takes place at the ____ and deletion at the ____.
Show answer
Answer: A — rear, front
Enqueue adds at the rear and dequeue removes from the front. The reverse order would break FIFO.A deque (double-ended queue) allows insertion and deletion at:
Show answer
Answer: A — Both ends
A deque is open at both ends. A queue restricts insertion to the rear and deletion to the front.Which of the following is an application of a queue?
Show answer
Answer: A — Scheduling jobs for a CPU in order of arrival
Jobs served in order of arrival are queued. Undo, bracket checks and postfix evaluation use a stack.What is the output of the following code?
q = []for x in [3, 6, 9]:q.append(x)q.pop(0)q.append(12)print(q)Show answer
Answer: B — [6, 9, 12]
The list is [3, 6, 9]; pop(0) removes the front element 3 and 12 joins the rear, giving [6, 9, 12]. "[3, 6, 12]" removes the rear element instead and "[3, 6, 9, 12]" forgets the dequeue.What is the output of the following code?
d = []d.append(1)d.insert(0, 2)d.append(3)d.pop()print(d)Show answer
Answer: B — [2, 1]
The list becomes [1], then [2, 1], then [2, 1, 3], and pop() removes the rear element 3, leaving [2, 1]. "[2, 1, 3]" forgets the pop and "[1]" removes the front.Assertion (A): A deque can be used both as a stack and as a queue.
Reason (R): Insertion and deletion are permitted at both ends, so it can follow either LIFO or FIFO.
Choose the correct option:Show answer
Answer: A — Both A and R are true and R is the correct explanation of A
Using one end only gives a stack and using opposite ends gives a queue, which R states. Option 2 is wrong.Consider the following statements:
A. Enqueue adds an element at the rear of a queue.
B. A deque permits insertion and deletion at both ends.
C. Dequeue removes an element from the rear of a queue.
D. A queue is empty when it has no elements.
Choose the correct answer:Show answer
Answer: A — A, B and D only
A, B and D are correct. C is false because dequeue removes from the front, so option 4 is the trap.Match List I with List II:
List I:
A. Enqueue;
B. Dequeue;
C. Front;
D. Underflow
List II:
1. Trying to remove from an empty queue;
2. Insert at the rear;
3. Remove from the front;
4. Position of the next element to be removedShow answer
Answer: A — A-2, B-3, C-4, D-1
Enqueue inserts at the rear (2), dequeue removes from the front (3), front marks the next element out (4) and underflow is removing from an empty queue (1). Option 2 swaps enqueue and dequeue.What is the output of the following code?
q = [5, 7]q.append(q.pop(0) + q[0])print(q)Show answer
Answer: A — [7, 12]
pop(0) removes 5, leaving [7]; q[0] is then 7, so 5 + 7 = 12 is appended, giving [7, 12]. "[12]" forgets that 7 remains and "[5, 12]" keeps the removed element.What is the output of the following code?
q = [1, 2, 3, 4]st = []while q:st.append(q.pop(0))while st:q.append(st.pop())print(q)Show answer
Answer: B — [4, 3, 2, 1]
Moving the queue into a stack and back reverses the order, giving [4, 3, 2, 1]. "[1, 2, 3, 4]" ignores the LIFO reversal, and "[4, 1, 2, 3]" reverses only one element.What is the output of the following code?
dq = ["r", "a", "d", "a", "r"]ok = Truewhile len(dq) > 1:if dq.pop(0) != dq.pop():ok = Falseprint(ok, len(dq))Show answer
Answer: A — True 1
Comparing front and rear pairs finds r=r and a=a, and one element d remains, so the result is True 1. "True 0" assumes an even count leaves nothing.What is the output of the following code?
q = [1, 2, 3, 4, 5]for _ in range(2):q.append(q.pop(0))print(q)Show answer
Answer: B — [3, 4, 5, 1, 2]
Each step moves the front element to the rear; after two steps 1 and 2 are at the end: [3, 4, 5, 1, 2]. "[2, 3, 4, 5, 1]" does one rotation only.Starting with an empty queue, 10, 20, 30 and 40 are enqueued; two dequeues follow; then 50 is enqueued. The front and rear elements are:
Show answer
Answer: A — 30 and 50
The two dequeues remove 10 and 20, leaving 30, 40 and then 50, so front is 30 and rear is 50. "20 and 50" removes only one element.What is the output of the following code?
d = [10, 20, 30]d.insert(0, d.pop())d.append(d.pop(0))print(d)Show answer
Answer: B — [10, 20, 30]
pop() takes 30 and inserts it at the front giving [30, 10, 20]; pop(0) takes it again and appends it at the rear, restoring [10, 20, 30]. The other lists stop partway.Assertion (A): A circular rotation of a queue moves the front element to the rear.
Reason (R): This is done by a dequeue followed by an enqueue of the same element.
Choose the correct option:Show answer
Answer: A — Both A and R are true and R is the correct explanation of A
Remove from the front, add at the rear: that is the rotation, as R says. Option 2 is wrong.