By WebNest Studio Engineering Team
Python Tutorial
Arrays, Stacks and Queues in Python
Classic data structures appear constantly in real programs and coding interviews: arrays of numbers, stacks (last in, first out) for undo and expression parsing, and queues (first in, first out) for task processing and breadth-first search. Python has no separate "array" keyword, but it gives you efficient tools for all of them.
This lesson covers the array module, implementing stacks with lists, queues with collections.deque, priority queues with heapq, and the thread-safe queue module.
Why it matters
Undo history, the browser's back button and checking matching brackets are stacks. Print jobs, background tasks and requests waiting for a server are queues. Python has no separate stack or queue type in everyday use; you choose the right built-in structure, and choosing the wrong one makes a program slow.
The array Module
array.array(typecode, items) stores numbers of one type compactly, like arrays in C — for example 'i' for signed ints and 'd' for doubles. It uses much less memory than a list of Python ints. For numerical computing, NumPy arrays (see the NumPy lesson) are the more powerful choice.
Stacks (LIFO)
A list is a perfect stack: append() pushes and pop() pops from the end, both O(1). Stacks power undo history, browser back buttons, matching brackets and depth-first search.
Queues (FIFO)
Do not use list.pop(0) for queues — it is O(n) because every item shifts. collections.deque supports O(1) append and popleft at both ends, and a maxlen for bounded buffers.
Priority Queues and Thread-Safe Queues
heapq turns a list into a min-heap: heappush and heappop always return the smallest item in O(log n) — ideal for scheduling by priority and Dijkstra's algorithm. queue.Queue, LifoQueue and PriorityQueue add locking for producer/consumer threads.
Examples
The array module
from array import array
import sys
temps = array("d", [21.5, 23.0, 19.8])
temps.append(25.1)
temps.extend([18.0, 22.4])
print(temps, temps[1], len(temps))
print(max(temps), round(sum(temps) / len(temps), 2))
ints = array("h", range(1000)) # "h" = 2-byte signed integers
print(sys.getsizeof(ints) < sys.getsizeof(list(range(1000))))
try:
ints.append(3.5)
except TypeError as e:
print("TypeError:", e)
array('d', [21.5, 23.0, 19.8, 25.1, 18.0, 22.4]) 23.0 6
25.1 21.63
True
TypeError: 'float' object cannot be interpreted as an integer
Stack: checking balanced brackets
def balanced(expression):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in expression:
if ch in "([{":
stack.append(ch) # push
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]: # pop
return False
return not stack
for e in ["(a + b) * [c]", "{[()]}", "(]", "((x)"]:
print(e, "->", balanced(e))
(a + b) * [c] -> True
{[()]} -> True
(] -> False
((x) -> False
Queue with deque, and a bounded recent-items buffer
from collections import deque
tasks = deque(["email", "report", "backup"])
tasks.append("cleanup")
print("processing", tasks.popleft())
print("processing", tasks.popleft())
print("remaining", list(tasks))
recent = deque(maxlen=3)
for page in ["home", "courses", "python", "fastapi", "pricing"]:
recent.append(page)
print("last 3 pages:", list(recent))
recent.rotate(1)
print(list(recent))
processing email
processing report
remaining ['backup', 'cleanup']
last 3 pages: ['python', 'fastapi', 'pricing']
['pricing', 'python', 'fastapi']
Priority queue with heapq
import heapq
tickets = []
heapq.heappush(tickets, (3, "Change avatar"))
heapq.heappush(tickets, (1, "Payment failed"))
heapq.heappush(tickets, (2, "Cannot log in"))
while tickets:
priority, title = heapq.heappop(tickets)
print(priority, title)
print(heapq.nlargest(2, [40, 10, 90, 70]), heapq.nsmallest(2, [40, 10, 90, 70]))
1 Payment failed
2 Cannot log in
3 Change avatar
[90, 70] [10, 40]
Common Mistakes
- Using list.pop(0) or insert(0, x) for queues — O(n); use deque.
- Expecting heapq to be a max-heap — it is a min-heap; negate priorities for max.
- Mixing types in array.array, which only accepts its declared type.
- Using plain lists shared between threads instead of queue.Queue.
Exercise
Use a deque as a queue: serve the first two customers, printing each name, and then print who is still waiting. Then use a list as a stack: push 1, 2 and 3 and print the value that comes off the top.
Expected output: Asha, Ravi, ['Zoya'], 3 (one per line)
from collections import deque
queue = deque(["Asha", "Ravi", "Zoya"])
# TODO: remove and print the first two customers
# TODO: print the remaining queue as a list
stack = []
# TODO: push 1, 2 and 3, then pop and print the top value
Show hints
queue.popleft()removes and returns the item at the front.- For a stack,
appendpushes andpop()removes the last item added.
Show solution
from collections import deque
queue = deque(["Asha", "Ravi", "Zoya"])
print(queue.popleft())
print(queue.popleft())
print(list(queue))
stack = []
stack.append(1)
stack.append(2)
stack.append(3)
print(stack.pop())
Quick quiz
1. In which order does a stack return its items?
- A. First in, first out
- B. Last in, first out
- C. Sorted order
- D. Random order
Show answer
B. The most recently added item is removed first.
2. Why is list.pop(0) a poor way to implement a queue?
- A. It does not work
- B. It removes the last item
- C. Every remaining item is shifted one place, so it is O(n)
- D. It returns None
Show answer
C. deque.popleft() does the same job in constant time.
3. Which item does heapq.heappop(heap) return?
- A. The item added first
- B. The item added last
- C. The largest item
- D. The smallest item
Show answer
D. heapq maintains a min-heap, which is how a priority queue is built.
Interview questions
How do you implement a stack and a queue in Python?
Show answer
A stack is a list: append() pushes and pop() removes from the same end, both in constant time. A queue is a collections.deque: append() adds at the back and popleft() removes from the front, both in constant time. For passing work between threads, queue.Queue adds the necessary locking.
What is a priority queue and how is one built in Python?
Show answer
A priority queue always returns the item with the highest priority and not the oldest. The heapq module provides it on top of an ordinary list: heappush adds an item and heappop removes the smallest, each in O(log n). Items are usually tuples of (priority, value), so that they are ordered by priority.
Key Points to Remember
- array.array stores same-typed numbers compactly.
- Lists are efficient stacks with append/pop.
- collections.deque is the right queue: O(1) append/popleft, optional maxlen.
- heapq provides priority queues (min-heap).
- queue.Queue is thread-safe for producer/consumer code.
Practice in the playground
Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.
Run the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.
Written by
WebNest Studio Engineering Team
Practical lessons from developers working with Java, Python, React, databases and production systems.
Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering