In Python, what is the difference between ".append()" and "+= []"?
For your case the only difference is performance: append is twice as fast.
Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> import timeit>>> timeit.Timer('s.append("something")', 's = []').timeit()0.20177424499999999>>> timeit.Timer('s += ["something"]', 's = []').timeit()0.41192320500000079Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> import timeit>>> timeit.Timer('s.append("something")', 's = []').timeit()0.23079359499999999>>> timeit.Timer('s += ["something"]', 's = []').timeit()0.44208112500000141
In general case append
will add one item to the list, while +=
will copy all elements of right-hand-side list into the left-hand-side list.
Update: perf analysis
Comparing bytecodes we can assume that append
version wastes cycles in LOAD_ATTR
+ CALL_FUNCTION
, and += version -- in BUILD_LIST
. Apparently BUILD_LIST
outweighs LOAD_ATTR
+ CALL_FUNCTION
.
>>> import dis>>> dis.dis(compile("s = []; s.append('spam')", '', 'exec')) 1 0 BUILD_LIST 0 3 STORE_NAME 0 (s) 6 LOAD_NAME 0 (s) 9 LOAD_ATTR 1 (append) 12 LOAD_CONST 0 ('spam') 15 CALL_FUNCTION 1 18 POP_TOP 19 LOAD_CONST 1 (None) 22 RETURN_VALUE>>> dis.dis(compile("s = []; s += ['spam']", '', 'exec')) 1 0 BUILD_LIST 0 3 STORE_NAME 0 (s) 6 LOAD_NAME 0 (s) 9 LOAD_CONST 0 ('spam') 12 BUILD_LIST 1 15 INPLACE_ADD 16 STORE_NAME 0 (s) 19 LOAD_CONST 1 (None) 22 RETURN_VALUE
We can improve performance even more by removing LOAD_ATTR
overhead:
>>> timeit.Timer('a("something")', 's = []; a = s.append').timeit()0.15924410999923566
In the example you gave, there is no difference, in terms of output, between append
and +=
. But there is a difference between append
and +
(which the question originally asked about).
>>> a = []>>> id(a)11814312>>> a.append("hello")>>> id(a)11814312>>> b = []>>> id(b)11828720>>> c = b + ["hello"]>>> id(c)11833752>>> b += ["hello"]>>> id(b)11828720
As you can see, append
and +=
have the same result; they add the item to the list, without producing a new list. Using +
adds the two lists and produces a new list.
>>> a=[]>>> a.append([1,2])>>> a[[1, 2]]>>> a=[]>>> a+=[1,2]>>> a[1, 2]
See that append adds a single element to the list, which may be anything. +=[]
joins the lists.