DEV Community

Muhammed H. Alkan
Muhammed H. Alkan

Posted on

Extend is sometimes faster than Append

I just was comparing the performance difference between [].append(x) and [] + [x]. I just realized [].append(x) was faster. But when i tried it with [].extend([x]) is faster. You just can use it while optimizing your code. Do not use it while you're coding, but when you're going to optimize it use [].extend([x]). Simple benchmarks

>>> import timeit
>>> start = timeit.timeit()
>>> [1, 2, 3, 4] + [5]
[1, 2, 3, 4, 5]
>>> end = timeit.timeit()
>>> end - start
0.006420466001145542
>>> start = timeit.timeit()
>>> [1, 2, 3, 4].append(5)
>>> end = timeit.timeit()
>>> end - start
0.004373588995804312
>>> start = timeit.timeit()
>>> [1, 2, 3, 4].extend([5])
>>> end = timeit.timeit()
>>> end - start
0.0022365170007105917

Results for the first benchmark

Fastest: [1, 2, 3, 4].extend([5])
0.0022365170007105917 seconds

Medium: [1, 2, 3, 4].append(5)
0.004373588995804312 seconds

Slowest: [1, 2, 3, 4] + [5]
0.006420466001145542 seconds

Second benchmarks from CLI

lambdef ~ λ python -mtimeit -s'[1, 2, 3, 4] + [5]'
100000000 loops, best of 3: 0.00939 usec per loop
lambdef ~ λ python -mtimeit -s'[1, 2, 3, 4].append(5)'
100000000 loops, best of 3: 0.00938 usec per loop
lambdef ~ λ python -mtimeit -s'[1, 2, 3, 4].extend([5])'
100000000 loops, best of 3: 0.00993 usec per loop

Results for the second benchmark

Fastest: [1, 2, 3, 4].append(5)
100000000 loops, best of 3: 0.00938 usec per loop

Medium: [1, 2, 3, 4] + [5]
100000000 loops, best of 3: 0.00939 usec per loop

Slowest: [1, 2, 3, 4].extend([5])
100000000 loops, best of 3: 0.00993 usec per loop

So when you add items continuously, you should prefer .append(), otherwise you should use .extend().

Top comments (0)