AW Dev Rethought

✂️ Perfection is achieved not when there is nothing more to add, but when there is nothing left to take away - Antoine de Saint-Exupéry

🔬 Python Code Lab — append() vs extend() 🐍


Description:

A page of prices arrives as [20, 30]. Your list already holds 10. Before starting a stopwatch, decide what should occupy the next slot.

a, b = [10], [10]
a.append([20, 30])
b.extend([20, 30])
print(a)  # [10, [20, 30]]
print(b)  # [10, 20, 30]

Appending keeps the pair together as one object. Extending visits the iterable and adds each element. To compare speed fairly, both versions should produce the same list. Python list methods


Experiment 1 · Individual values

We built a flat list of 4,096 integers from a prebuilt input list. Calling out.append(x) for each value took 56.6 µs per build. Calling out.extend([x]) took 135.6 µs. The latter constructs a fresh one-element list every time.


Experiment 2 · Existing batches

Now suppose the same integers arrive in prebuilt lists. The two builders differ only in how they transfer each batch into a fresh output.

def by_item(batches):
    out = []
    for batch in batches:
        for x in batch:
            out.append(x)
    return out

def by_batch(batches):
    out = []
    for batch in batches:
        out.extend(batch)
    return out
Items per prebuilt batch Append loop (µs/build) Extend batch (µs/build)
1 147.5 89.4
8 74.6 25.9
64 67.4 13.3
4,096 56.0 7.1

Both approaches do work proportional to the number of items. With batches of 64, extend() makes 64 Python-level method calls to transfer the same values that take 4,096 append() calls.

Why does even the width-one row look different from Experiment 1? Here, singleton lists already exist. The append builder has to loop inside each one. In Experiment 1, the extend builder had to create each singleton.


When does the difference matter?

With batches of 64, both builders added 4,096 elements. One made 4,096 Python-level append calls. The other made 64 extend calls. That saved 54.1 µs per complete build in this run. That difference is small for an occasional list, but worth checking when list construction sits in a frequently repeated path.

These are local CPython 3.13.5 timings on macOS arm64. Each number is the median of nine round averages, with 100 fresh builds per round and shuffled method order. We checked output equality before timing. The timer included output construction and cleanup. Input generation and batch slicing were outside the timer. If your application creates batches solely for this optimization, include that work in your measurement. Python timeit

Use append when one object belongs in the next slot. Use extend when an iterable’s elements belong there separately.


Link copied!

Comments

Add Your Comment

Comment Added!