Updated for Python 3.12+ Β· June 2026

Big-O & Complexity
Measure how code scales

A complete, practical guide to Big-O notation in Python β€” how to read it, how to derive it from real code, and how to use it to pick the right data structure before performance becomes a problem.

complexity.py
def find_duplicates(items):
    seen = set()          # O(1) membership
    duplicates = []
    for item in items:     # O(n) loop
        if item in seen:      # O(1) lookup
            duplicates.append(item)
        seen.add(item)        # O(1) insert
    return duplicates
# Overall: O(n) time, O(n) space
$ python complexity.py
[3, 1]
# 1000 items: ~1 ms Β· 1,000,000 items: ~1 s

πŸ“ˆ Why Big-O Matters

It predicts how code behaves as inputs grow β€” before you ship it

Complexity Is About Growth, Not Speed

Big-O notation describes how the cost of an algorithm grows as the input size grows. It doesn't tell you how many milliseconds a function takes β€” it tells you whether doubling the input doubles the time, quadruples it, or barely changes it at all.

That distinction matters because small inputs hide bad algorithms. A quadratic function that runs in a millisecond on 100 items takes 100 seconds on 10,000 items. You may not notice the problem during development and discover it only when real data arrives.

The practical payoff is choosing the right data structure before you write the code. Knowing that a list lookup is O(n) and a set lookup is O(1) is often the difference between a fast program and a slow one β€” and it requires no profiling at all, because the answer follows from the structure of the code.

Big-O is an upper bound

Formally, O(f(n)) means "grows no faster than f(n)" β€” it's a ceiling, not an exact count. Two functions that are both O(n) can differ by a constant factor of 100x. Big-O tells you what happens when the input gets large, not how fast a specific run will be.

  • βœ“Read and write Big-O notation for time and space
  • βœ“Recognise the common complexity classes and what they mean in practice
  • βœ“Derive complexity from real Python code
  • βœ“Know the complexity of Python's built-in data structures
  • βœ“Use Big-O to choose between a list, a set, and a dict
  • βœ“Avoid the most common hidden-complexity traps in Python

πŸ”€ Reading the Notation

What O(1), O(n), and O(nΒ²) actually mean

Big-O describes the shape of the growth curve. The letter n stands for the size of the input β€” the number of items in a list, the number of characters in a string, the number of nodes in a graph. The expression inside the parentheses says how cost scales with that size.

NotationNameWhat it means
O(1)ConstantCost doesn't change with input size
O(log n)LogarithmicCost grows slowly β€” each step halves the problem
O(n)LinearCost scales directly with input size
O(n log n)LinearithmicSlightly worse than linear β€” typical of good sorting
O(nΒ²)QuadraticCost scales with the square β€” nested loops
O(2ⁿ)ExponentialCost doubles with each added input β€” intractable
O(n!)FactorialCombinatorial explosion β€” brute-force permutations

How the curves compare

n = 10         n = 100          n = 1,000
─────────────────────────────────────────────────────
O(1)       1             1                1
O(log n)   3             7                10
O(n)       10            100              1,000
O(n log n) 33            664              9,966
O(nΒ²)      100           10,000           1,000,000
O(2ⁿ)      1,024         10³⁰             impractical
Look at the last column. At n = 1,000, the difference between O(n) and O(nΒ²) is a factor of 1,000. At n = 1,000,000 it's a factor of a million. That's why complexity matters: the gap widens as inputs grow.

Dropping constants

Big-O ignores constant factors and lower-order terms. Both of the functions below are O(n), even though one does three operations per item and the other does one:

def one_operation_per_item(items):
    total = 0
    for item in items:
        total += item
    return total
# O(n) β€” one pass

def three_operations_per_item(items):
    total = 0
    for item in items:
        total += item
        total += 1
        total += 2
    return total
# Also O(n) β€” constant factor of 3x, but same growth shape

Dropping constants doesn't mean they don't matter in practice β€” a 3x difference is real. It means they don't change the shape of the curve, and Big-O is about shape.

Keeping only the dominant term

def mixed_complexity(items):
    for item in items:        # O(n)
        print(item)
    for a in items:          # O(nΒ²) nested loop
        for b in items:
            print(a, b)
# Total: O(n) + O(nΒ²) = O(nΒ²) β€” the dominant term wins

When two terms are added, keep the one that grows faster. O(nΒ² + n) simplifies to O(nΒ²), because for large n the quadratic part dominates.

🏷️ The Common Complexity Classes

What each one looks like in real code

⚑

O(1) β€” Constant

Best

Cost is independent of input size. Dictionary lookups, arithmetic, and indexing by position are all O(1).

def first_item(items):
    return items[0]        # O(1) β€” indexing a list is constant

def lookup(mapping, key):
    return mapping[key]        # O(1) β€” dict lookup

def add(a, b):
    return a + b               # O(1) β€” arithmetic
πŸ”

O(log n) β€” Logarithmic

Excellent

Each step halves the remaining work. Binary search is the classic example. A 1,000,000-item search takes about 20 steps.

def binary_search(sorted_items, target):
    lo, hi = 0, len(sorted_items) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if sorted_items[mid] == target:
            return mid
        elif sorted_items[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1
# Each iteration halves the search space: O(log n)
πŸ“

O(n) β€” Linear

Good

Cost scales directly with input size. A single pass over a collection. Doubling the input doubles the time.

def find_max(items):
    best = items[0]
    for item in items:        # one pass
        if item > best:
            best = item
    return best

def sum_all(items):
    total = 0
    for item in items:        # one pass
        total += item
    return total
πŸ”€

O(n log n) β€” Linearithmic

Fair

A linear pass that also does logarithmic work per item. This is the complexity of efficient sorting algorithms like merge sort and Python's sorted().

def merge_sort(items):
    if len(items) <= 1:
        return items
    mid = len(items) // 2
    left = merge_sort(items[:mid])
    right = merge_sort(items[mid:])
    return merge(left, right)

# log n levels of recursion Γ— O(n) merge per level = O(n log n)
πŸ”

O(nΒ²) β€” Quadratic

Slow

Nested loops over the same collection. For 10,000 items, that's 100 million operations. Often avoidable with a set or dict.

def find_duplicates_slow(items):
    duplicates = []
    for i in range(len(items)):          # O(n)
        for j in range(i + 1, len(items)):  # O(n) inner
            if items[i] == items[j]:
                duplicates.append(items[i])
    return duplicates
# O(nΒ²) β€” for 10k items, ~50M comparisons
πŸ’₯

O(2ⁿ) β€” Exponential

Very Slow

Each additional input doubles the work. Naive recursive Fibonacci is the textbook example. Only viable for very small inputs.

def fib_naive(n):
    if n < 2:
        return n
    return fib_naive(n - 1) + fib_naive(n - 2)
# O(2ⁿ) β€” fib(40) takes about 2 billion calls
The rule of thumb for sorting: O(n log n) is the best you can do with comparison-based sorting. Python's sorted() and .sort() use Timsort, which is O(n log n) in the worst case and O(n) on already-sorted data.

πŸ’Ύ Space Complexity

Memory grows too β€” measure it the same way

Space complexity describes how memory usage grows with input size. It uses the same notation as time complexity: O(1) means constant extra memory, O(n) means memory proportional to input size, and so on.

space_complexity.py
# O(1) space β€” uses a fixed number of variables
def sum_in_place(items):
    total = 0
    for item in items:
        total += item
    return total

# O(n) space β€” allocates a new list proportional to input
def double_all(items):
    result = []
    for item in items:
        result.append(item * 2)
    return result

# O(n) space β€” a set can grow to the size of the input
def unique_items(items):
    return list(set(items))

Trading space for time

A common optimization is to spend more memory to save time. The find_duplicates example from the hero is exactly this: a set uses O(n) extra memory, but turns an O(nΒ²) nested loop into an O(n) single pass.

def find_duplicates_slow(items):
    duplicates = []
    for i in range(len(items)):
        for j in range(i + 1, len(items)):
            if items[i] == items[j]:
                duplicates.append(items[i])
    return duplicates
# Time: O(nΒ²) Β· Space: O(1) extra

def find_duplicates_fast(items):
    seen = set()
    duplicates = []
    for item in items:
        if item in seen:
            duplicates.append(item)
        seen.add(item)
    return duplicates
# Time: O(n) Β· Space: O(n) extra
The classic trade-off: almost every speed optimization costs memory. Big-O lets you reason about the trade explicitly instead of discovering it when the process gets OOM-killed in production.
Recursion uses stack space. A recursive function that recurses n levels deep uses O(n) space even if it allocates no other structures. Python's default recursion limit is about 1,000 frames.

πŸ“Š Python Data Structure Complexity

The table you'll come back to

Python's built-in collections have well-defined complexity. Knowing these means you can choose the right one without measuring. The table below covers the most common operations.

List

OperationComplexityNotes
items[i]O(1)Index access
items.append(x)O(1) amortizedOccasionally O(n) for resize
items.pop()O(1)Removes from the end
items.insert(0, x)O(n)Shifts every element
x in itemsO(n)Linear search
items.remove(x)O(n)Search plus shift
items.sort()O(n log n)Timsort

Dict

OperationComplexityNotes
d[key]O(1) averageHash lookup
d[key] = valueO(1) averageHash insert
key in dO(1) averageHash membership
d.get(key)O(1) averageSafe lookup
del d[key]O(1) averageHash delete
for k in dO(n)Iteration

Set

OperationComplexityNotes
x in sO(1) averageHash membership
s.add(x)O(1) averageHash insert
s.remove(x)O(1) averageHash delete
s | tO(len(s) + len(t))Union
s & tO(min(len(s), len(t)))Intersection
s - tO(len(s))Difference

Deque (collections.deque)

OperationComplexityNotes
d.append(x)O(1)Add to the right
d.appendleft(x)O(1)Add to the left
d.pop()O(1)Remove from the right
d.popleft()O(1)Remove from the left
d[i]O(n)Index access is slow
The most important row: x in list is O(n) but x in set is O(1). This single fact accounts for more performance improvements in real Python code than any other. If you're checking membership inside a loop, use a set.

String operations

OperationComplexityNotes
s[i]O(1)Index access
s + tO(len(s) + len(t))Concatenation
sub in sO(len(s) Γ— len(sub))Substring search
s.split(sep)O(len(s))Splitting
s.upper()O(len(s))Case conversion
Building a string with += in a loop is O(nΒ²), because each concatenation copies the existing string. Use "".join(parts) instead β€” it's O(n).

πŸ”¬ Deriving Complexity From Code

A step-by-step method

The method is simple: count the loops, look at what happens inside them, and combine the pieces. Most real code falls into a handful of patterns once you start looking.

analysis_examples.py
# 1. Single loop over the input: O(n)
def count_positive(items):
    count = 0
    for item in items:
        if item > 0:
            count += 1
    return count

# 2. Two sequential loops: O(n) + O(n) = O(n)
def count_and_sum(items):
    count = 0
    for item in items:
        count += 1
    total = 0
    for item in items:
        total += item
    return count, total

# 3. Nested loops over the same input: O(nΒ²)
def pairs(items):
    result = []
    for a in items:
        for b in items:
            result.append((a, b))
    return result

# 4. Loop that halves: O(log n)
def count_doublings(n):
    steps = 0
    while n > 1:
        n = n // 2
        steps += 1
    return steps

# 5. Loop with a set inside: O(n)
def has_duplicates(items):
    seen = set()
    for item in items:        # O(n)
        if item in seen:      # O(1)
            return True
        seen.add(item)
    return False

# 6. Loop with a list search inside: O(nΒ²)
def has_duplicates_slow(items):
    seen = []
    for item in items:        # O(n)
        if item in seen:      # O(n)
            return True
        seen.append(item)
    return False

The three questions

  • How many times does each loop run?
  • What is the cost of the operations inside the loop?
  • Do the loops nest, or run sequentially?

Nested loops multiply. Sequential loops add. A loop that halves the problem each iteration is logarithmic. A loop with an O(1) operation inside is O(n); a loop with an O(n) operation inside is O(nΒ²).

Hidden complexity in Python

What looks cheapActuallyWhy
x in some_listO(n)Linear scan
list.insert(0, x)O(n)Shifts every element
s += char in a loopO(nΒ²)Each concatenation copies
some_list[1:]O(n)Creates a new list
list.pop(0)O(n)Shifts every element
sorted(x) inside a loopO(nΒ² log n)Sorts on every iteration
The most expensive line in Python is often the one that looks cheapest. x in items reads like a single operation but is a full scan on a list. Switching to a set is a one-line fix that turns O(nΒ²) into O(n).

Optimizing with the right structure

# Before: O(n Γ— m) β€” for each item in a, scan all of b
def common_slow(a, b):
    result = []
    for item in a:
        if item in b:        # O(m) scan of list b
            result.append(item)
    return result

# After: O(n + m) β€” build a set once, then O(1) lookups
def common_fast(a, b):
    b_set = set(b)              # O(m) one-time cost
    return [item for item in a if item in b_set]
    # O(n) total

# Even simpler: set intersection is O(min(len(a), len(b)))
def common_fastest(a, b):
    return list(set(a) & set(b))

This is the pattern behind most real-world Python performance fixes: replace a list membership test with a set membership test, or replace a nested loop with a dictionary lookup.

πŸ—οΈ Mini Project β€” Three Ways to Find Duplicates

Measure the difference Big-O predicts

This program implements three versions of "find duplicates" with different complexity classes, then measures them at increasing input sizes so you can see the curves diverge.

duplicates_benchmark.py
import time
import random

def dupes_quadratic(items):
    seen = []
    dupes = []
    for item in items:        # O(n)
        if item in seen:      # O(n) list scan
            dupes.append(item)
        else:
            seen.append(item)
    return dupes
# Time: O(nΒ²)

def dupes_linear(items):
    seen = set()
    dupes = []
    for item in items:        # O(n)
        if item in seen:      # O(1) set lookup
            dupes.append(item)
        else:
            seen.add(item)
    return dupes
# Time: O(n)

def dupes_counter(items):
    from collections import Counter
    counts = Counter(items)    # O(n)
    return [item for item, count in counts.items() if count > 1]
# Time: O(n)

def benchmark(fn, n):
    data = [random.randint(0, n // 2) for _ in range(n)]
    start = time.perf_counter()
    fn(data)
    return time.perf_counter() - start

sizes = [500, 1000, 2000, 4000]

print(f"{'n':>8} {'quadratic':>12} {'linear':>12} {'counter':>12}")
for n in sizes:
    t_q = benchmark(dupes_quadratic, n)
    t_l = benchmark(dupes_linear, n)
    t_c = benchmark(dupes_counter, n)
    print(f"{n:>8} {t_q:>11.4f}s {t_l:>11.4f}s {t_c:>11.4f}s")

The output will show the quadratic version growing roughly 4x each time the input doubles, while the linear versions grow roughly 2x. That's the O(nΒ²) versus O(n) signature in raw numbers β€” and it's exactly what the theory predicted.

The point of the exercise: at n = 500 the three versions look comparable. At n = 4,000 the quadratic one is already noticeably slower. At n = 100,000 it becomes unusable. Big-O tells you this in advance so you don't ship the wrong version.

❓ Frequently Asked Questions

Common questions about Big-O and complexity

You need the small subset that covers built-in data structures: list lookup is O(n), set and dict lookup is O(1), nested loops multiply. That subset prevents most performance bugs and requires almost no effort to learn. The full formalism is more useful for algorithm design than for writing application code.

Not necessarily. For small inputs, a simple O(nΒ²) algorithm can be faster than a complex O(n log n) one because of lower constant factors. The problem is that "small" is often larger than you think. If the input might grow, prefer the better complexity; if it's genuinely bounded at a small size, the simpler code is fine.

O(n log n) in the worst case, O(n) on already-sorted data. Python uses Timsort, a hybrid merge-and-insertion sort that exploits existing order. In practice it's one of the fastest general-purpose sorts, which is why you should almost never write your own.

Yes. Each s += x creates a new string and copies all existing characters. Doing this n times copies 1 + 2 + ... + n characters, which is O(nΒ²). Use "".join(parts) instead β€” it allocates once and copies each piece exactly once, for O(n) total.

Sets are implemented as hash tables. Checking membership computes the hash of the value and jumps directly to the corresponding bucket, which is a constant-time operation. List membership has to scan element by element, which is O(n). The trade-off is that sets use more memory and require hashable elements.

Dict and set operations are O(1) on average but O(n) in the worst case, if every key collides into the same bucket. In practice Python's hash functions make this rare for typical data, but it's the reason the docs say "average" rather than just O(1). For strings specifically, hash randomization (enabled by default) prevents adversarial collision attacks.

Usually time, because users notice slow responses but rarely notice a few extra megabytes. The standard trade is: spend memory to save time. Build a set or dict once, then do O(1) lookups instead of O(n) scans. Exceptions exist β€” embedded systems, huge datasets, and processes with tight memory limits β€” but for typical applications, time is the constraint.

Measure it. Write a small benchmark that runs the code at a few input sizes and plots or prints the timings. If doubling the input roughly doubles the time, you have O(n). If it quadruples, you have O(nΒ²). If it barely changes, you probably have O(1) or O(log n). The analysis gives you a hypothesis; the measurement confirms it.