Coding

Big O Notation Explained, with Real Python Timings

Big O notation describes how an algorithm's running time (or memory) grows as the input size n grows, ignoring constant factors. O(n) means doubling the input roughly doubles the work; O(n²) means doubling the input roughly quadruples it; O(1) means the work stays the same however large the input gets.

The common complexities at a glance

NotationNameWork when n goes from 1,000 to 1,000,000Python example
O(1)ConstantSamed[key], x in some_set, lst[i]
O(log n)LogarithmicAbout 2 times (log₂ goes from about 10 to about 20)bisect.bisect_left on a sorted list
O(n)Linear1,000 timesx in some_list, one loop over the data
O(n log n)LinearithmicAbout 2,000 timessorted(), list.sort()
O(n²)Quadratic1,000,000 timesA loop inside a loop over the same data
O(2ⁿ)ExponentialNot feasibleNaive recursive Fibonacci

The third column is the arithmetic of each function, not a measurement. The measurements are next.

Measured: what these growth rates look like in Python

We timed common operations with Python's timeit module on one machine: an Intel Core i7-13700H laptop with 64 GB of RAM, Windows 11, Python 3.12.2. Each figure is the best of 5 repeats (3 for sorting); the timeit documentation recommends taking the minimum, because higher values usually come from other processes interfering rather than from Python itself. Your absolute numbers will differ; the ratios between rows are what matter, and repeated runs on this machine varied by roughly 10 to 30% for the small timings.

import timeit, bisect, random

for n in (1_000, 10_000, 100_000, 1_000_000):
    data = list(range(n))
    s = set(data)
    target = n - 1                      # last element: worst case for a list scan
    t_list = min(timeit.repeat(lambda: target in data, number=100, repeat=5)) / 100
    t_set  = min(timeit.repeat(lambda: target in s,    number=100, repeat=5)) / 100
    t_bis  = min(timeit.repeat(lambda: bisect.bisect_left(data, target), number=100, repeat=5)) / 100
    shuffled = data[:]; random.seed(1); random.shuffle(shuffled)
    t_sort = min(timeit.repeat(lambda: sorted(shuffled), number=3, repeat=3)) / 3

Results:

nx in list O(n)x in set O(1)bisect O(log n)sorted() O(n log n)
1,0003.52 µs0.067 µs0.170 µs0.040 ms
10,00033.19 µs0.045 µs0.125 µs0.853 ms
100,000373.15 µs0.045 µs0.144 µs13.512 ms
1,000,0004,324.93 µs0.047 µs0.161 µs223.581 ms

What to read from it:

  • The list scan grows linearly. Each tenfold increase in n made it roughly ten times slower: 3.5 µs, 33 µs, 373 µs, 4.3 ms.
  • The set lookup stays flat at about 0.05 µs from a thousand items to a million. At one million items it was about 90,000 times faster than the list. Most of that 0.05 µs is the overhead of the timing call itself.
  • Binary search barely moves. log₂ of a million is about 20, so a million-item search needs about 20 comparisons. The small differences between rows are mostly noise.
  • Sorting grows a little faster than linear. From 100,000 to 1,000,000 items, the time grew about 16.5 times for a tenfold increase in n, where n log n alone predicts about 12 times. We didn't investigate the difference; big O ignores hardware effects such as memory caching, so real timings rarely follow the curve exactly.

Measured: what O(n²) feels like

Here are two ways to check a list for duplicates. The first compares every pair; the second uses a set:

def has_dup_quadratic(xs):          # O(n²)
    for i in range(len(xs)):
        for j in range(i + 1, len(xs)):
            if xs[i] == xs[j]:
                return True
    return False

def has_dup_set(xs):                # O(n)
    return len(set(xs)) != len(xs)

Timed on lists with no duplicates (the worst case for the first function), same machine:

nNested loopsSet
1,00056.1 ms0.039 ms
2,000155.1 ms0.075 ms
4,000810.8 ms0.080 ms

Going from 1,000 to 4,000 items (4 times as many) made the nested loop about 14 times slower, close to the 16 times that n² predicts. At 4,000 items it already takes most of a second. Following the same curve, 100,000 items would need roughly 625 times longer than 4,000 items, several minutes, while the set version would still finish in milliseconds. That gap is why big O matters: the slow version looks fine in a test with 50 rows and falls over in production.

The formal definition, briefly

NIST's Dictionary of Algorithms and Data Structures defines it this way: f(n) = O(g(n)) means there are positive constants c and k such that 0 ≤ f(n) ≤ c·g(n) for all n ≥ k. In words, past some input size, f never grows faster than g times a constant.

Two practical rules follow from that:

  • Drop constants. 3n + 10 is O(n). A loop that does five things per item is still linear.
  • Keep only the fastest-growing term. NIST's own example: n² + 3n + 4 is O(n²), because it is less than 2n² for all n above 10.

Strictly, big O is an upper bound. NIST notes it is often misused to mean "equal to", where Θ (big Theta) is the precise term. In everyday use, when people say "this is O(n)" they usually mean Θ(n).

How to work out the big O of your code

  1. Find what grows. Name the input size: number of items, characters, rows.
  2. Count loops over it. One loop over n items is O(n). A loop inside a loop over the same items is O(n²). Two separate loops one after the other are O(n) + O(n) = O(n).
  3. Look inside library calls. A line that looks constant can hide a loop. x in some_list is O(n), lst.insert(0, x) is O(n), and lst.pop(0) is O(n), because the rest of the list has to shift. Put one of those inside a loop and the loop becomes O(n²).
  4. Halving means log n. If each step throws away half the remaining data, like binary search, the step count is about log₂ n.

Recursion needs a little more care: count how many calls are made in total. See recursion explained, where naive Fibonacci makes 2.7 million calls for n = 30.

Big O of Python's built-in types

From the Python documentation's time complexity page, which covers CPython (other implementations may differ):

OperationComplexityNote
lst[i], lst.append(x)O(1)append is amortized: occasionally O(n) when storage is resized
lst.pop() (last item)O(1)Nothing has to move
lst.pop(0), lst.insert(0, x)O(n)Every other item shifts
x in lstO(n)Scans until found
lst.sort()O(n log n)Already sorted or reversed input takes only O(n) comparisons
d[key], d[key] = v, key in dO(1) averageO(n) worst case if every key hashes to the same value
x in s (set)O(1) averageSame worst case as dict

The single most useful habit from this table: if you test membership inside a loop, use a set or dict, not a list.

What big O doesn't tell you

  • Actual speed at small sizes. At n = 1,000 the list scan took 3.5 µs. If you do it a few times per request, it doesn't matter.
  • Constant factors. Two O(n) functions can differ a lot in practice, for example a pure-Python loop against a built-in function that does the same work in C.
  • Average vs worst case. Dict lookups are O(1) on average and O(n) in the worst case. Say which one you mean.
  • Memory. The set-based duplicate check is faster but uses O(n) extra memory to hold the set. Space complexity uses the same notation.

Measure when it matters. Big O tells you which approach will survive as data grows; timeit tells you how fast it is today.

Frequently asked questions

Is O(1) always faster than O(n)?
No. Big O describes how cost grows, not the actual time. An O(1) operation with a large constant cost can be slower than an O(n) loop over a small list. Big O tells you which approach wins as the input gets large, so measure when inputs are small.
What is the difference between big O, big Omega and big Theta?
Big O is an upper bound: the cost grows no faster than the given function, up to a constant. Big Omega is a lower bound. Big Theta means both at once, a tight bound. NIST's definition notes that big O is often used loosely to mean 'equal to' when Theta is the precise term.
What does amortized O(1) mean?
It means the operation is O(1) on average over many calls, even though an individual call is occasionally more expensive. Python's list.append is the standard example: it is usually constant time, but now and then the list's storage has to be resized, which costs O(n). Spread over many appends, the average stays constant.
Does big O measure memory too?
It can. The same notation describes space complexity, meaning how much extra memory an algorithm needs as input grows. A function that builds a set of all n items uses O(n) extra space; one that only keeps a running total uses O(1).

Sources