list.extend vs. list addition

list.extend seems to be slower than extending a list using +=


In [1]:
%%timeit

l = [1, 2]
l.extend([3, 4])


249 ns ± 12.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [2]:
%%timeit

l = [1, 2]
l += [3, 4]


182 ns ± 3.04 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

Disassembler

The disassembler shows that the extra function call and the attribute loading (extend method of list) are necessary for the first version.


In [3]:
def extend_list(l):
    l.extend([3, 4])
    
def extend_list_with_add(l):
    l += [3, 4]

In [4]:
import dis

dis.dis(extend_list)


  2           0 LOAD_FAST                0 (l)
              2 LOAD_ATTR                0 (extend)
              4 LOAD_CONST               1 (3)
              6 LOAD_CONST               2 (4)
              8 BUILD_LIST               2
             10 CALL_FUNCTION            1
             12 POP_TOP
             14 LOAD_CONST               0 (None)
             16 RETURN_VALUE

In [5]:
dis.dis(extend_list_with_add)


  5           0 LOAD_FAST                0 (l)
              2 LOAD_CONST               1 (3)
              4 LOAD_CONST               2 (4)
              6 BUILD_LIST               2
              8 INPLACE_ADD
             10 STORE_FAST               0 (l)
             12 LOAD_CONST               0 (None)
             14 RETURN_VALUE