---
title: Stack Data Structure: Operations, Python Code, Examples
url: https://www.masaischool.com/resources/stack-data-structure-explained
description: What a stack is, push and pop in O(1), array vs linked-list code in Python, the call stack, balanced brackets and next greater element, with real output.
updated: 2026-12-01
publisher: Masai (https://www.masaischool.com)
---

# Stack data structure: how it works, with Python code

> **Short answer**
>
> **A stack** is a linear data structure that follows last in, first out (LIFO): the item you added most recently is the first one removed. Its core operations are push (add on top), pop (remove from top) and peek (read the top), and each takes O(1) time in both array and linked-list implementations.

This page is for students who have seen the definition of a stack and want to see it work: both implementations, the call stack that runs your own code, and two problems that interviewers reuse often. Every code block was executed on Python 3.9.6 on 1 December 2026 and the output shown is what it printed.

For where stacks are used in real software (undo, browsers, compilers), see [applications of stack in data structure](https://www.masaischool.com/resources/applications-of-stack-in-data-structure). This page is about how to build one and how to think with one.

## What is a stack and which operations does it support?

A stack is a collection where insertion and removal happen at one end only, called the top. That rule gives last in, first out (LIFO) order. A pile of plates is the usual picture: you add to the top and take from the top, never from the middle.

| Operation | What it does | Time | Notes |
|---|---|---|---|
| push(x) | Put x on top | O(1) | Amortised O(1) with a dynamic array |
| pop() | Remove and return the top | O(1) | Fails on an empty stack (underflow) |
| peek() / top() | Read the top without removing it | O(1) | Also fails on empty |
| is_empty() | True if no items | O(1) | Check this before pop and peek |
| size() | Number of items | O(1) | Kept as a counter or len() |
| search(x) | Find x anywhere | O(n) | Not what a stack is for; you would use a hash set |

Two error names come up in exams. **Overflow** means pushing onto a full stack (only possible in a fixed-size array). **Underflow** means popping or peeking an empty one. Python lists grow on demand, so you only meet underflow.

## Stack implementation in Python: array vs linked list

You can back a stack with a dynamic array (a Python list) or a linked list. Both give O(1) push and pop. The difference is memory layout and what else you can do. For the general trade-off see [array vs linked list](https://www.masaischool.com/resources/array-vs-linked-list-difference) and [linked list explained](https://www.masaischool.com/resources/linked-list-explained).

### Array-backed stack

The top of the stack is the end of the list, because append and pop() at the end are cheap. Never use the front: pop(0) shifts every item.class ArrayStack: def __init__(self): self._items = [] def push(self, x): self._items.append(x) def pop(self): if not self._items: raise IndexError("pop from empty stack") return self._items.pop() def peek(self): return self._items[-1] def is_empty(self): return not self._items def __len__(self): return len(self._items) s = ArrayStack() for x in [10, 20, 30]: s.push(x) print(s.pop(), s.peek(), len(s)) try: ArrayStack().pop() except IndexError as e: print("error:", e)30 20 2 error: pop from empty stack

### Linked-list stack

The top is the head of the list. Pushing makes a new node that points at the old head, and popping moves the head one step along. No shifting and no resizing, but each item costs a separate node object.class Node: __slots__ = ("value", "next") def __init__(self, value, next=None): self.value, self.next = value, next class LinkedStack: def __init__(self): self.head = None self.size = 0 def push(self, x): self.head = Node(x, self.head) # new node becomes the head self.size += 1 def pop(self): if self.head is None: raise IndexError("pop from empty stack") node = self.head self.head = node.next self.size -= 1 return node.value def peek(self): return self.head.value s = LinkedStack() for x in "abc": s.push(x) print(s.pop(), s.peek(), s.size)c b 2

|  | Array (Python list) | Linked list |
|---|---|---|
| push / pop | O(1) amortised, occasional resize copy | O(1) worst case |
| Memory | Compact, spare capacity at the end | One node object per item plus pointer |
| Fixed size possible | Yes (classic exam version) | No need, grows per node |
| Typical use in Python | Default choice: list or collections.deque | Teaching, or when you must avoid resize pauses |

In real Python code, use a plain list as a stack. The standard library has no separate Stack class; the [Python tutorial](https://docs.python.org/3/tutorial/datastructures.html) shows append and pop as the stack idiom. JavaScript is the same: push and pop on an array.const stack = []; stack.push(1); stack.push(2); stack.push(3); console.log(stack.pop(), stack[stack.length - 1], stack.length);

## The call stack: the stack you use without noticing

Every function call pushes a frame (arguments, local variables, return address) on the call stack, and returning pops it. This is why recursion works, and why it has a limit. Python caps the depth with sys.getrecursionlimit(), documented in the [sys module](https://docs.python.org/3/library/sys.html).import sys def depth(n): return 0 if n == 0 else 1 + depth(n - 1) print(depth(500)) print("limit:", sys.getrecursionlimit()) try: depth(5000) except RecursionError as e: print("RecursionError:", e) # the same count with an explicit stack: no call-stack limit def depth_iter(n): stack, count = [n], 0 while stack: k = stack.pop() if k > 0: count += 1 stack.append(k - 1) return count print(depth_iter(5000))500 limit: 1000 RecursionError: maximum recursion depth exceeded in comparison 5000

The first call goes 500 frames deep and is fine. The second goes 5,000 deep, passes the default limit of 1,000 and raises RecursionError. The last function does the same counting with a list as an explicit stack, so the depth is limited by memory rather than by the interpreter. Converting recursion to a loop with your own stack is a standard interview follow-up; see [recursion vs iteration](https://www.masaischool.com/resources/recursion-vs-iteration-difference).

## Worked example 1: balanced brackets

Problem: given a string, check that every (, [ and { is closed by the matching bracket in the right order. Idea: push each opening bracket; on a closing bracket, the top of the stack must be its partner. If not, the string is wrong at that index. If the stack is not empty at the end, something was never closed.def balanced(text): pairs = {")": "(", "]": "[", "}": "{"} stack = [] for i, ch in enumerate(text): if ch in "([{": stack.append(ch) elif ch in pairs: if not stack or stack.pop() != pairs[ch]: return False, i return (not stack), (len(text) if stack else None) for t in ["{[()]}", "([)]", "((", "a[b(c)d]e", ")("]: print(repr(t), balanced(t))'{[()]}' (True, None) '([)]' (False, 2) '((' (False, 2) 'a[b(c)d]e' (True, None) ')(' (False, 0)

Read the output: ([)] fails at index 2 because the top is [ when ) arrives. (( fails at the end (index 2 is the string length) because two brackets stay open. )( fails at once because there is nothing to pop. Time is O(n), space is O(n) in the worst case.

## Worked example 2: next greater element

Problem: for each number, find the first larger number to its right, or -1. The brute force is two nested loops, O(n squared). A stack gives O(n): keep the indices of numbers still waiting for an answer. When a bigger number arrives, it is the answer for every smaller waiting number on top of the stack.def next_greater(nums): result = [-1] * len(nums) stack = [] # indices still waiting for a greater value for i, x in enumerate(nums): while stack and nums[stack[-1]] < x: result[stack.pop()] = x stack.append(i) return result print(next_greater([4, 5, 2, 25])) print(next_greater([13, 7, 6, 12])) print(next_greater([3, 2, 1]))[5, 25, 25, -1] [-1, 12, 12, -1] [-1, -1, -1]

Each index is pushed once and popped once, so the inner while loop does at most n pops in total across the whole run. That is why the nested-looking code is still O(n). This monotonic stack pattern also solves daily temperatures, largest rectangle in a histogram and stock span. For how to count loops like this, see [time complexity and Big O](https://www.masaischool.com/resources/time-complexity-and-big-o-explained).

## Stack vs queue and what to practise next

Stack is LIFO, [queue](https://www.masaischool.com/resources/queue-data-structure-explained) is first in, first out. If a problem needs the most recent item, think stack. If it needs the oldest, think queue. Depth-first search uses a stack (or recursion); breadth-first search uses a queue.

- Evaluate a postfix expression (push numbers, pop two on each operator).
- Min stack: a stack that returns the minimum in O(1) using a second stack.
- Valid parentheses with a count of the longest valid substring.
- Reverse a string or a linked list using a stack, then without one.
- Implement a queue using two stacks, then the reverse.

More problems sit in [DSA interview questions](https://www.masaischool.com/resources/dsa-interview-questions). The full order of topics is on the [data structures and algorithms learning path](https://www.masaischool.com/resources/data-structures-and-algorithms).

## Frequently asked questions

### What is a stack in a data structure?

A stack is a linear collection where you add and remove items at one end only, the top. Because the newest item leaves first, it is called last in, first out (LIFO). It supports push, pop, peek and an empty check, and each runs in constant time.

### What is the difference between push and pop?

Push adds an item to the top of the stack. Pop removes the top item and returns it. Peek reads the top without removing it. Pop and peek on an empty stack cause an underflow error, so check for emptiness first.

### How do you implement a stack in Python?

Use a list: append(x) to push and pop() to pop from the end, and stack[-1] to peek. Both are O(1) amortised. You can also write a class around a list or a linked list, which is what exams usually ask for.

### Is a stack faster as an array or a linked list?

Both are O(1) for push and pop. In practice the array version is usually faster in Python and C because items sit together in memory and there is no per-item node allocation. A linked list never needs a resize copy, which matters only in unusual real-time cases.

### What is a stack overflow?

In data structures it means pushing onto a full fixed-size stack. In programs it usually means the call stack ran out of space, often from recursion with no base case. Python reports this as a RecursionError once the depth passes the recursion limit, 1,000 by default.

### Where is a stack used?

Function calls and recursion, undo and redo, browser back navigation, checking brackets in compilers and editors, and depth-first search. The applications page linked above goes through each with examples.
