append on lists

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Tue Sep 16 01:03:59 CEST 2008


On Mon, 15 Sep 2008 13:47:53 -0700, Chris Rebert wrote:

> The code you'd actually want is:
> 
> d = a[:] #copy a
> d.append(7)
> 
> Or if you're willing to overlook the inefficiency:
> 
> d = a + [7]
> 
> But that's not idiomatic.

Why is a + [7] more inefficient than manually copying the list and 
appending to the copy? Surely both pieces of code end up doing the same 
thing?

In fact, I'd guess that the second is likely to be marginally more 
efficient than the first:


>>> x = compile('d = a[:]; d.append(7)', '', 'exec')
>>> dis.dis(x)
  1           0 LOAD_NAME                0 (a)
              3 SLICE+0
              4 STORE_NAME               1 (d)
              7 LOAD_NAME                1 (d)
             10 LOAD_ATTR                2 (append)
             13 LOAD_CONST               0 (7)
             16 CALL_FUNCTION            1
             19 POP_TOP
             20 LOAD_CONST               1 (None)
             23 RETURN_VALUE

>>> x = compile('d = a + [7]', '', 'exec')
>>> dis.dis(x)
  1           0 LOAD_NAME                0 (a)
              3 LOAD_CONST               0 (7)
              6 BUILD_LIST               1
              9 BINARY_ADD
             10 STORE_NAME               1 (d)
             13 LOAD_CONST               1 (None)
             16 RETURN_VALUE


timeit agrees with me:

>>> from timeit import Timer
>>> t1 = Timer('d = a[:]; d.append(7)', 'a = []')
>>> t2 = Timer('d = a + [7]', 'a = []')
>>> t1.repeat(number=1000)
[0.0015339851379394531, 0.0014910697937011719, 0.0014841556549072266]
>>> t2.repeat(number=1000)
[0.0011889934539794922, 0.0013048648834228516, 0.0013070106506347656]


-- 
Steven



More information about the Python-list mailing list