Stack or queue: LIFO and FIFO

Stacks and queues Junior Python 3.13+ Reviewed By Best Latest Apps

Predict the output

What does this print?

Python 3.13
from collections import deque
items = [1, 2, 3]
stack = list(items)
queue = deque(items)
print(stack.pop(), queue.popleft())

Options

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A 3 1

Right: the stack hands back the newest item, the queue the oldest.

The same three items leave in opposite orders, which is the whole difference between the two structures.

Why not the others?
  • B 1 1. list.pop() takes from the end.
  • C 3 3. popleft takes from the front.

30-second answer

A stack is last in, first out: the newest item leaves first (undo, matching brackets, depth-first search). A queue is first in, first out: the oldest item leaves first (BFS, scheduling, buffering). In Python use a list as a stack and collections.deque as a queue; in Kotlin ArrayDeque serves as both. All the core operations are O(1).

Practise saying it · 30 s. No recording, just a timer

Compare stacks and queues.

Say your answer out loud, then check which of these points you covered:

  • LIFO vs FIFO
  • list vs deque in Python
  • Uses of each

Deep dive

A deque supports both ends, so it can be either; say which end you treat as the front.

Priority queues are not FIFO: they hand out the smallest (or largest) item first and are usually heaps.

Thread-safe queues (queue.Queue) add locking for producer-consumer code.

Common mistakes

  • Using list.pop(0) as a queue.
  • Calling a heap a queue and expecting arrival order.

Senior take & follow-ups

Pick the structure by asking 'newest first or oldest first?'.

Follow-up questions

Think of your answer first, then open the hint.

  1. How is the call stack related?

    Show hint

    Each function call pushes a frame; returning pops it. Recursion depth is stack depth.

  2. What is a circular buffer?

    Show hint

    A fixed-size array with head and tail indexes that wrap around: a queue with no reallocation.

Similar on Android: Channels The Android page covers Kotlin channels that pass values between coroutines in order; this page compares stacks and queues as data structures.

What each operation costs: Stack · Queue · Deque

From the author

DSA Master - Data & Algorithms

Free on iPhone and iPad: watch 50+ data structures and algorithms step through animations, run the code in the playground, and try the daily challenge.

Suggest a fix if something here is wrong or out of date.