145

What is the difference between:

some_list1 = []
some_list1.append("something")

and

some_list2 = []
some_list2 += ["something"]
agf
  • 171,228
  • 44
  • 289
  • 238
Nope
  • 34,682
  • 42
  • 94
  • 119

13 Answers13

179

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 win32
Type "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.41192320500000079

Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32
Type "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
Constantin
  • 27,478
  • 10
  • 60
  • 79
  • 14
    +1: This is very interesting. I use append anyway, because it results in clearer code. But I didn't realize there was a performance difference. If anything, I would have expected append to be slower, since it's a guaranteed function call, while I presumed += would be optimized further. – DNS Apr 07 '09 at 14:37
  • 3
    Isn't there also a functional difference? For instance let **a = []**, **b = [4,5,6]**, here if you do **c = a.append(b)** then c would be a list of list **[[4,5,6]]** while **c += b**; would lead to a simple list **c = [4,5,6]**. – rph Jul 04 '16 at 12:59
  • 1
    just to set things straight: += gives a better performance than extend or append as long as your input is in the right format. What takes time in the current example is the creation of the ['something'] list. += is about 15% faster – Joe Sep 20 '16 at 16:58
  • 1
    @Joe If you're comparing `append` vs `+=`, then you *must* include creation of the list as part of the measurement. Otherwise it'd be a different question (`extend` vs `+=`). – jamesdlin Sep 28 '16 at 05:15
  • 1
    @jamesdlin yup! But it's easy to be mistaken unless you already know this. A little additional precision has never hurt anyone, right? – Joe Sep 29 '16 at 12:36
  • 1
    @rph No, there is no functional difference. To comply with the question, your example should be `c += [b]` instead of `c += b`, so you missed the brackets. – matheburg Jun 30 '20 at 12:48
57
>>> 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.

dwc
  • 24,196
  • 7
  • 44
  • 55
  • 2
    Voting this up because this is an important distinction between the two. Good work. –  Apr 07 '09 at 14:26
53

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.

DNS
  • 37,249
  • 18
  • 95
  • 132
  • 1
    There *is* difference between append and +=. – Constantin Apr 07 '09 at 14:26
  • 3
    There's the fact that `append` adds one entry to the list, while += adds as many as there are in the other list (i.e. aliases to `extend`). But he/she knows that already, judging by the way the question was written. Is there some other difference I'm missing? – DNS Apr 07 '09 at 14:33
  • 1
    There's a difference because an augmented assignment introduces rebinding (explanation in my answer). – bobince Apr 07 '09 at 15:34
32

+= is an assignment. When you use it you're really saying ‘some_list2= some_list2+['something']’. Assignments involve rebinding, so:

l= []

def a1(x):
    l.append(x) # works

def a2(x):
    l= l+[x] # assign to l, makes l local
             # so attempt to read l for addition gives UnboundLocalError

def a3(x):
    l+= [x]  # fails for the same reason

The += operator should also normally create a new list object like list+list normally does:

>>> l1= []
>>> l2= l1

>>> l1.append('x')
>>> l1 is l2
True

>>> l1= l1+['x']
>>> l1 is l2
False

However in reality:

>>> l2= l1
>>> l1+= ['x']
>>> l1 is l2
True

This is because Python lists implement __iadd__() to make a += augmented assignment short-circuit and call list.extend() instead. (It's a bit of a strange wart this: it usually does what you meant, but for confusing reasons.)

In general, if you're appending/extended an existing list, and you want to keep the reference to the same list (instead of making a new one), it's best to be explicit and stick with the append()/extend() methods.

bobince
  • 528,062
  • 107
  • 651
  • 834
22
 some_list2 += ["something"]

is actually

 some_list2.extend(["something"])

for one value, there is no difference. Documentation states, that:

s.append(x) same as s[len(s):len(s)] = [x]
s.extend(x) same as s[len(s):len(s)] = x

Thus obviously s.append(x) is same as s.extend([x])

vartec
  • 131,205
  • 36
  • 218
  • 244
  • 1
    s.append takes an arbitrary type and adds it to the list; It's a true append. s.extend takes an iterable (usually a list), and merges the iterable into s, modfiying the memory addresses of s. These are *not* the same. – W4t3randWind Mar 31 '18 at 16:39
10

The difference is that concatenate will flatten the resulting list, whereas append will keep the levels intact:

So for example with:

myList = [ ]
listA = [1,2,3]
listB = ["a","b","c"]

Using append, you end up with a list of lists:

>> myList.append(listA)
>> myList.append(listB)
>> myList
[[1,2,3],['a','b','c']]

Using concatenate instead, you end up with a flat list:

>> myList += listA + listB
>> myList
[1,2,3,"a","b","c"]
Alex Shroyer
  • 3,499
  • 2
  • 28
  • 54
SRC2
  • 101
  • 1
  • 2
6

The performance tests here are not correct:

  1. You shouldn't run the profile only once.
  2. If comparing append vs. +=[] a number of times, you should declare append as a local function.
  3. Time results are different on different python versions: 64- and 32-bit.

e.g.

timeit.Timer('for i in xrange(100): app(i)', 's = [] ; app = s.append').timeit()

Good tests can be found here: Python list append vs. +=[]

tdy
  • 36,675
  • 19
  • 86
  • 83
Michael
  • 2,827
  • 4
  • 30
  • 47
  • still, the += tests in that page uses `+= [one_var]`. If we omit creating lists, += becomes the fastest option. – Joe Sep 20 '16 at 17:00
3

In addition to the aspects described in the other answers, append and +[] have very different behaviors when you're trying to build a list of lists.

>>> list1=[[1,2],[3,4]]
>>> list2=[5,6]
>>> list3=list1+list2
>>> list3
[[1, 2], [3, 4], 5, 6]
>>> list1.append(list2)
>>> list1
[[1, 2], [3, 4], [5, 6]]

list1+['5','6'] adds '5' and '6' to the list1 as individual elements. list1.append(['5','6']) adds the list ['5','6'] to the list1 as a single element.

Chris Upchurch
  • 15,297
  • 6
  • 51
  • 66
3

The rebinding behaviour mentioned in other answers does matter in certain circumstances:

>>> a = ([],[])
>>> a[0].append(1)
>>> a
([1], [])
>>> a[1] += [1]
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

That's because augmented assignment always rebinds, even if the object was mutated in-place. The rebinding here happens to be a[1] = *mutated list*, which doesn't work for tuples.

Reinstate Monica
  • 4,568
  • 1
  • 24
  • 35
2

"+" does not mutate the list

.append() mutates the old list

Andres
  • 731
  • 2
  • 10
  • 22
1

As of today and Python 3.6, the results provided by @Constantine are no longer the same.

Python 3.6.10 |Anaconda, Inc.| (default, May  8 2020, 02:54:21) 
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> timeit.Timer('s.append("something")', 's = []').timeit()
0.0447923709944007
>>> timeit.Timer('s += ["something"]', 's = []').timeit()
0.04335783299757168

It seems that append and += now have an equal performance, whereas the compilation differences haven't changed at all:

>>> import dis
>>> dis.dis(compile("s = []; s.append('spam')", '', 'exec'))
  1           0 BUILD_LIST               0
              2 STORE_NAME               0 (s)
              4 LOAD_NAME                0 (s)
              6 LOAD_ATTR                1 (append)
              8 LOAD_CONST               0 ('spam')
             10 CALL_FUNCTION            1
             12 POP_TOP
             14 LOAD_CONST               1 (None)
             16 RETURN_VALUE
>>> dis.dis(compile("s = []; s += ['spam']", '', 'exec'))
  1           0 BUILD_LIST               0
              2 STORE_NAME               0 (s)
              4 LOAD_NAME                0 (s)
              6 LOAD_CONST               0 ('spam')
              8 BUILD_LIST               1
             10 INPLACE_ADD
             12 STORE_NAME               0 (s)
             14 LOAD_CONST               1 (None)
             16 RETURN_VALUE
RobBlanchard
  • 855
  • 3
  • 17
0

let's take an example first

list1=[1,2,3,4]
list2=list1     (that means they points to same object)

if we do 
list1=list1+[5]    it will create a new object of list
print(list1)       output [1,2,3,4,5] 
print(list2)       output [1,2,3,4]

but if we append  then 
list1.append(5)     no new object of list created
print(list1)       output [1,2,3,4,5] 
print(list2)       output [1,2,3,4,5]

extend(list) also do the same work as append it just append a list instead of a 
single variable 
Avnish Nishad
  • 1,634
  • 1
  • 17
  • 18
0

The append() method adds a single item to the existing list

some_list1 = []
some_list1.append("something")

So here the some_list1 will get modified.

Updated:

Whereas using + to combine the elements of lists (more than one element) in the existing list similar to the extend (as corrected by Flux).

some_list2 = []
some_list2 += ["something"]

So here the some_list2 and ["something"] are the two lists that are combined.

  • 1
    This is wrong. `+=` does not return a new list. The [Programming FAQ](https://docs.python.org/3/faq/programming.html#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works) says: "... for lists, `__iadd__` is equivalent to calling `extend` on the list and returning the list. That's why we say that for lists, `+=` is a "shorthand" for `list.extend`". You can also see this for yourself in the CPython source code: https://github.com/python/cpython/blob/v3.8.2/Objects/listobject.c#L1000-L1011 – Flux Mar 07 '20 at 01:04