Lesson 3 / 6

Stacks, Queues and Linked Lists

Stacks — Last In, First Out

stack = []nstack.append("Lesson 1")   # pushnstack.append("Lesson 2")nstack.append("Lesson 3")nlast = stack.pop()          # "Lesson 3" -- removes and returns the most recently added item

A stack only ever adds or removes from one end — think of a stack of plates, where you can only take from the top. The browser’s back button, an “undo” feature, and how function calls themselves are tracked during execution all use a stack under the hood.

Queues — First In, First Out

from collections import dequennqueue = deque()nqueue.append("Student A")   # enqueuenqueue.append("Student B")nfirst = queue.popleft()      # "Student A" -- removes from the opposite end it was added to

A queue processes items in the order they arrived — a real-world line at a checkout counter. Task queues, print queues, and request handling in many backend systems are built on this exact idea.

Linked lists

class Node:n    def __init__(self, value):n        self.value = valuen        self.next = Nonennfirst = Node("Lesson 1")nfirst.next = Node("Lesson 2")nfirst.next.next = Node("Lesson 3")nncurrent = firstnwhile current:n    print(current.value)n    current = current.next

Unlike an array, a linked list’s elements are not stored next to each other in memory — each node holds a value and a pointer/reference to the next node. This makes inserting or removing an item from the middle very cheap (no shifting every subsequent element, unlike an array), at the cost of losing instant index-based access — reaching the 1000th item means walking through the 999 before it.

Choosing the right one

Reach for a stack when order needs to reverse (last thing in comes out first). Reach for a queue when order needs to be preserved (first thing in comes out first). Reach for a linked list when you expect frequent insertions/removals in the middle of a sequence and don’t need fast random access.