Python Stacks, Queues & TreesGet Certified
What Are Stacks, Queues, and Trees?
Stacks, queues, and trees are classic data structures, which are organized ways of storing data so that a program can use it efficiently. A stack and a queue both hold a sequence of items, but they differ in the order that items come out. A tree arranges items in a hierarchy, like the folders on your computer or the sections of a company.
Python does not have separate built-in types for these three structures, but you can build all of them from tools you already know: lists, collections.deque, and classes. Learning them is valuable because they appear everywhere in real software, from the Back button of a web browser and the Undo command of a word processor to print queues, file systems, and search engines. They are also favorite topics in technical interviews.
- Stack: last in, first out (LIFO). The newest item is the first one removed, like a stack of plates.
- Queue: first in, first out (FIFO). The oldest item is removed first, like a line at a store.
- Tree: a hierarchy of nodes, where each node can have child nodes below it.
- Binary tree: a tree in which every node has at most two children, called left and right.
- Binary search tree: a binary tree that keeps smaller values on the left and larger values on the right.
- Traversal: visiting every node of a tree in a planned order, such as depth-first or breadth-first.
Stacks: Last In, First Out
A stack works like a pile of plates: you put a new plate on top, and you also take the next plate from the top. The two basic operations are push, which adds an item, and pop, which removes the most recent item. Looking at the top item without removing it is called peek.
A Python list makes an excellent stack. The method append() pushes an item onto the end, pop() removes and returns the last item, and stack[-1] peeks at it. Both append() and pop() at the end of a list are very fast. The Back button of a browser is a stack: each page you visit is pushed, and pressing Back pops the most recent one.
Try It: A Browser’s Back Button
Click Test My Code to run the program. Then push another page and pop two pages.
stack = []
stack.append("Home")
stack.append("Products")
stack.append("Checkout")
print(stack)
print(stack.pop())
print(stack[-1])
print(len(stack))
print(stack)append() pushes "Home" onto the top of the stack.['Home', 'Products', 'Checkout']. The last item is the top.pop() removes and returns the last item, like pressing the Back button. The output is Checkout.stack[-1] reads the last item without removing it. The output is Products.2.['Home', 'Products'].Using a Stack to Check Balanced Brackets
One of the best-known uses of a stack is checking whether brackets are balanced, which is what a code editor does when it highlights a missing parenthesis. Every opening bracket is pushed onto the stack. When a closing bracket appears, it must match the opening bracket on top of the stack, which is the most recent one that is still waiting for a partner.
If the closing bracket does not match, or if there is nothing on the stack to match, the text is not balanced. At the end, the stack must be completely empty, or some opening brackets were never closed. The “last opened, first closed” rule is exactly the last-in, first-out behavior of a stack, which is why a stack is the natural tool for this job.
Try It: Check Brackets in an Expression
Click Test My Code. Then try your own expressions with different bracket mistakes.
def is_balanced(text):
stack = []
pairs = {")": "(", "]": "[", "}": "{"}
for char in text:
if char in "([{":
stack.append(char)
elif char in pairs:
if not stack or stack.pop() != pairs[char]:
return False
return len(stack) == 0
print(is_balanced("(a + b) * [c - d]"))
print(is_balanced("(a + b]"))
print(is_balanced("((2 + 3)"))is_balanced receives the text to check and returns True or False.elif char in pairs is true only for the three closing brackets, because the dictionary keys are the closing brackets.pop() removes the most recent opening bracket, which must equal the expected partner.False immediately.True.( is popped when ] arrives, but they do not match. The output is False.( is still on the stack at the end, so the output is False.Queues: First In, First Out
A queue works like a line of customers at a coffee shop: the person who arrived first is served first. Adding an item to the back is called enqueue, and removing an item from the front is called dequeue. Queues are used for print jobs, customer service tickets, and any situation where requests should be handled in the order they arrive.
You could use a list as a queue by removing items with pop(0), but that is slow for long lists, because every remaining item has to shift one place to the left. Python provides a better tool: collections.deque, pronounced “deck”, which stands for double-ended queue. Its methods append() and popleft() are both fast, no matter how many items the deque holds.
Try It: A Line at a Chicago Coffee Shop
Click Test My Code. Then add another customer and serve one more person.
deque as a queue of customers. Three people join the line, two of them are served in the order they arrived, and the program prints who is left.from collections import deque
line = deque()
line.append("Emily")
line.append("Jackson")
line.append("Olivia")
print(line)
print(line.popleft())
print(line.popleft())
print(list(line))
print(len(line))deque lives in the collections module. It is a fast double-ended queue.deque() creates an empty queue named line.append() adds a person at the back of the queue.deque(['Emily', 'Jackson', 'Olivia']). The front of the queue is on the left.popleft() removes and returns the item at the front. The output is Emily.Jackson.list(line) converts the queue into a list so it prints neatly. The output is ['Olivia'].1.Building a Queue Class
Wrapping a deque in a class gives you a clean queue with exactly the operations you need and nothing more. Users of the class call enqueue(), dequeue(), is_empty(), and size(), and they never have to think about the deque inside. This idea of hiding the details behind a simple interface is called abstraction.
A well-written queue should also behave sensibly when it is empty. Removing from an empty deque raises an IndexError, so the class below checks first and returns None when there is nothing to remove. The same design works for a stack: wrap a list and offer push(), pop(), and peek().
Try It: A Help Desk Ticket Queue
Click Test My Code. Then add a third ticket and dequeue it in order.
Queue class built on a deque, adds two support tickets, removes three times to show the order and the empty-queue behavior, and then checks whether the queue is empty.from collections import deque
class Queue:
def __init__(self):
self.items = deque()
def enqueue(self, item):
self.items.append(item)
def dequeue(self):
if self.is_empty():
return None
return self.items.popleft()
def is_empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
tickets = Queue()
tickets.enqueue("Printer jam")
tickets.enqueue("Wi-Fi down")
print(tickets.size())
print(tickets.dequeue())
print(tickets.dequeue())
print(tickets.dequeue())
print(tickets.is_empty())deque as its storage.Queue offers a small, clear set of operations.deque stored in self.items.enqueue adds an item to the back of the queue.append() places the item at the back.dequeue removes the item at the front.is_empty() on the same object before trying to remove anything.None instead of raising an error.popleft() removes and returns the oldest item.is_empty answers whether the queue holds any items.True only when there are no items.size reports how many items are waiting.len() counts the items in the deque.2.Printer jam.Wi-Fi down.None. The output is None.True.Trees: Hierarchical Data
A tree stores data in a hierarchy. The top item is called the root, every item is a node, the nodes directly below a node are its children, and a node with no children is a leaf. File systems are trees: a folder contains files and other folders. So is the organization of a country into states and cities.
In Python, a tree node is usually a small class that stores a value and a list of children. Because each child is itself the root of a smaller tree, the natural way to walk through a tree is with recursion, a function that calls itself. The function below prints a node, then calls itself on every child, adding two spaces of indentation for each level of depth.
Try It: States and Cities as a Tree
Click Test My Code. Then add another state and some cities of your own.
class Node:
def __init__(self, name):
self.name = name
self.children = []
def add(self, child):
self.children.append(child)
return child
usa = Node("USA")
texas = usa.add(Node("Texas"))
ohio = usa.add(Node("Ohio"))
texas.add(Node("Austin"))
texas.add(Node("Dallas"))
ohio.add(Node("Columbus"))
def show(node, depth=0):
print(" " * depth + node.name)
for child in node.children:
show(child, depth + 1)
show(usa)Node is one box in the tree.add attaches a child node below this node.texas refers to it.show prints a node and then everything below it. depth starts at 0 for the root.depth + 1, so the child’s subtree is printed beneath it.USA, then Texas indented once, Austin and Dallas indented twice, Ohio indented once, and Columbus indented twice.Binary Search Trees
A binary tree allows each node at most two children, called left and right. A binary search tree, or BST, adds one rule: every value in a node’s left subtree is smaller than the node, and every value in its right subtree is larger or equal. That rule makes searching fast, because each comparison lets you ignore half of the remaining tree.
To insert a value, start at the root and move left or right by comparing, until you reach an empty spot. A remarkable property follows: if you read a BST in in-order (left subtree, then the node, then right subtree), the values come out sorted. In a balanced tree, search and insertion take about log n steps. If values are inserted already sorted, however, the tree degenerates into a long chain and loses its speed.
Try It: Store Daily High Temperatures
Click Test My Code. Then add more temperatures to the list and check that the output stays sorted.
class BSTNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(node, value):
if node is None:
return BSTNode(value)
if value < node.value:
node.left = insert(node.left, value)
else:
node.right = insert(node.right, value)
return node
def inorder(node):
if node is None:
return []
return inorder(node.left) + [node.value] + inorder(node.right)
root = None
for temp in [68, 55, 72, 49, 61, 80]:
root = insert(root, temp)
print(inorder(root))
print(root.value, root.left.value, root.right.value)BSTNode is one node of a binary search tree.None means that there is no left child.insert places a value in the right spot below the given node and returns the node.None, the correct position has been reached.inorder collects the values of a tree into a sorted list.root is None because the tree is empty.[49, 55, 61, 68, 72, 80], even though the temperatures were inserted in a different order.68 55 72.Level-Order Traversal with a Queue
There are two main ways to visit every node of a tree. Depth-first traversal, like the recursive functions above, follows one branch all the way down before moving on to the next. Breadth-first traversal, also called level-order, visits all nodes on one level before moving to the next level down.
Breadth-first traversal uses a queue. You put the root in the queue, and then you repeat: remove the front node, visit it, and add its children to the back. Because a queue serves nodes in the order they arrived, the whole top level is processed before its children. The example below walks through the reporting structure of a company, which shows how a queue and a tree work together.
Try It: Walk Through a Company Chart
Click Test My Code. Then add a new manager under one of the vice presidents.
from collections import deque
org = {
"CEO": ["VP Sales", "VP Tech"],
"VP Sales": ["Manager Denver"],
"VP Tech": ["Manager Austin", "Manager Seattle"],
}
queue = deque(["CEO"])
while queue:
person = queue.popleft()
print(person)
for report in org.get(person, []):
queue.append(report)popleft() removes the person who has waited the longest.CEO, VP Sales, VP Tech, Manager Denver, Manager Austin, and Manager Seattle, in that order.org.get(person, []) returns the person’s reports, or an empty list for someone with no reports.Using a Stack with input()
Stacks are very handy for anything that has to be undone or reversed. Because the last item pushed is the first item popped, pushing a series of items and then popping them all returns the items in reverse order. This is a simple way to reverse a list, a word, or a route.
In the example below the user types a list of cities that they visited. The program pushes each city onto a stack, and then pops them one at a time to print the trip in reverse, which is the route back home. Remember that input() returns text, so split() is used to turn the line into a list of city names.
Try It: Plan the Return Trip
The Program Input box is already filled with one line: Boston Chicago Denver Seattle. Click Run Code straight away, then try your own list of cities separated by spaces.
line = input("Cities visited: ")
stack = []
for city in line.split():
stack.append(city)
print("Outbound:", " -> ".join(stack))
route_back = []
while stack:
route_back.append(stack.pop())
print("Return trip:", " -> ".join(route_back))
print("Stops:", len(route_back))input() reads the first line of the Program Input box as one string, such as "Boston Chicago Denver Seattle".split() breaks the text at the spaces, and the loop takes the city names one at a time." -> ".join(stack) glues the cities together with arrows. The output is Outbound: Boston -> Chicago -> Denver -> Seattle.pop() removes the top city, which is the most recent one, and appends it to the return list.Return trip: Seattle -> Denver -> Chicago -> Boston.Stops: 4.Tip: Python’s standard library also offersqueue.Queueandqueue.LifoQueue, which are safe to share between threads. For ordinary programs, a list for a stack and adequefor a queue are simpler and faster.
Common Mistakes with Stacks, Queues, and Trees
These data structures are simple in idea, but the details are easy to get wrong, especially which end of the sequence an operation works on. Most bugs come from mixing up last-in-first-out with first-in-first-out, from touching an empty structure, or from forgetting the base case in a recursive tree function. Read your code line by line and trace a tiny example by hand when something looks wrong.
- Mixing up LIFO and FIFO:
list.pop()removes the newest item (a stack), whiledeque.popleft()removes the oldest (a queue). - Popping from an empty structure:
[].pop()anddeque().popleft()raise anIndexError. Checkif stack:first. - Using list.pop(0) for a queue: it works, but it is slow for long lists. Use
collections.dequeinstead. - Forgetting the base case: a recursive tree function without
if node is None: returnkeeps calling itself until Python raises aRecursionError. - Forgetting to return the node in insert(): if a recursive
insertdoes not return the node, parent links are replaced byNoneand the tree loses its branches. - Sharing a children list:
children = []in the class body, instead of inside__init__, makes every node share one list. - Inserting sorted data into a plain BST: the tree becomes a long chain and searching becomes slow. Real programs use self-balancing trees.
- Changing a structure while looping over it: use a
while stack:orwhile queue:loop, and pop inside it, instead of aforloop over the same object.
Good Habits for Working with Data Structures
Choosing the right data structure is often more important than writing clever code. A few simple habits help you pick the right tool and use it safely. They also make your programs easier to read, because anyone who sees a stack or a queue immediately knows how the data is supposed to flow.
- Ask first: does the newest item or the oldest item need to be handled first? The answer tells you whether you need a stack or a queue.
- Use a list for a stack, and a
collections.dequefor a queue. Both give fast operations at the ends. - Wrap a structure in a small class when the same operations are used in many places, and expose only the methods that make sense.
- Always check whether a stack or queue is empty before removing an item, or return a safe default value.
- Write recursive tree functions with a clear base case first, then the recursive case.
- Test with tiny examples, such as an empty tree, a tree with one node, and a tree with three nodes.
- Remember that Python already provides sorted lists, dictionaries, and sets. Build your own structures to learn how they work, and use the built-in ones for most real tasks.
Key Takeaways
Stacks, queues, and trees give you reliable patterns for organizing data and for processing it in a particular order. Once you understand how items enter and leave each structure, many problems become straightforward. Review the points below before moving on to the scientific Python section of the course.
- A stack is last in, first out. Use
append()to push andpop()to remove from a list. - A queue is first in, first out. Use
append()andpopleft()on acollections.deque. - A stack is the natural tool for undo, backtracking, and matching brackets.
- A tree is a hierarchy of nodes, and recursion is the natural way to walk through it.
- A binary search tree keeps smaller values on the left and larger values on the right, and an in-order traversal returns sorted values.
- Breadth-first traversal uses a queue, and depth-first traversal uses recursion or a stack.
- Always handle the empty case, and give recursive functions a base case.
Frequently Asked Questions
Students often ask how these data structures differ, which Python tools to use, and why one is faster than another. The answers below summarize the most important points from the examples above. Open a question to read the answer, and run the matching example again if you want to see it in action.
What is a stack in Python?
A stack is a data structure that follows the last in, first out rule, so the most recently added item is the first one removed. In Python a list works well as a stack: append() pushes an item onto the end, pop() removes the last item, and stack[-1] looks at the top item without removing it.
What is a queue in Python?
A queue follows the first in, first out rule, so the oldest item is removed first. The best built-in tool is collections.deque, where append() adds an item to the back and popleft() removes the item at the front. Both operations are fast regardless of the size of the queue.
Why should I use deque instead of a list for a queue?
Removing the first item of a list with pop(0) forces Python to shift every other item one place to the left, which becomes slow as the list grows. A deque is designed for fast operations at both ends, so popleft() takes the same short time however many items the deque holds.
What is a tree data structure?
A tree is a hierarchy of nodes. The top node is the root, nodes directly below a node are its children, and nodes without children are leaves. Trees model folders and files, organization charts, and the structure of web pages. In Python a node is usually a class with a value and a list of children.
What is a binary search tree?
A binary search tree is a binary tree in which every node has at most two children and values in the left subtree are smaller than the node while values in the right subtree are larger or equal. This rule makes searching fast, and an in-order traversal returns the values in sorted order.
What is the difference between depth-first and breadth-first traversal?
Depth-first traversal follows one branch all the way down before backtracking, and it is usually written with recursion or a stack. Breadth-first traversal visits all nodes on one level before moving to the next level, and it uses a queue. Both visit every node exactly once.
What is the time complexity of stack and queue operations?
Pushing and popping at the end of a Python list takes constant time, written O(1), and so do append() and popleft() on a deque. Using list.pop(0) takes linear time, O(n). Searching a balanced binary search tree takes about O(log n) steps, but an unbalanced tree can degrade to O(n).
Where are stacks, queues, and trees used in real programs?
Stacks power the Back button, the Undo command, and bracket matching in editors. Queues handle print jobs, customer support tickets, and tasks waiting for a server. Trees represent file systems, organization charts, menus, and searchable indexes in databases. Many algorithms in this course rely on these three structures.