In Python, what is the difference between ".append()" and "+= []"?

python operator
difference between = and == in python
in python
in python means
difference between and in python
python is vs string
python not equal
what's the difference between the is operator and in python

What is the difference between:

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

and

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

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

What is the difference between 'is' and '==' in python, The is operator compares the identity of two objects while the == operator compares the values of two objects. There is a difference in meaning between equal and  The problem with tuples in Python is that they don’t have field names, and would be much more useful if they did. However, there is a namedtuple type in the collections module which solves this problem for us: That creates a new type named employee which has four fields: last, first, employee_num, and fulltime.

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.

What is the difference between = and == in Python?, Is there a difference between == and is in Python - In Python and many other programming languages, a single equal mark is used to assign a value to a  I think your talking about the division operators, but you used the wrong slash character. If you used the correct character then I don't know what you are talking about. / is floating point division so the result is a floating point type (double

>>> 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.

The Difference Between “is” and “==” in Python – dbader.org, There is no difference at runtime. The only difference between the two types of quotes is the one you have already pointed out: Single quotes  If A and B are two sets. The set difference of A and B is a set of elements that exists only in set A but not in B. The syntax of difference () method in Python is: Here, A and B are two sets. The following syntax is equivalent to A-B. The difference () method returns the difference of two sets which is also a set. It doesn't modify original sets.

+= 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.

What is the difference between ' ' and " " in python?, When using python I can run a script using both ' and " is there a difference that I should know about and do they perform differently? One symbol is a statement and the other is an operator. In Python = is a statement ( assignment statement ), it’s purpose is to create references and binding them (or rebind already created ones) to objects; it doesn’t create objects. On the other hand, the symbol == is an operator, the equality operator.

 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])

What is the difference between ' and " in python?, A box bracket pair denotes one of a list object, or an index subscript, my_List[x] . A curly brace pair denotes a dictionary object. We reference values in a  In Python, I'm not really clear on the difference between the following two lines of code: import X or from X import * Don't they both just import everything from the module X?

I don't get what is the difference between {} and [] in python, The is checks if both the variables point to the same object whereas the == sign checks if the values for the two variables are the same. So if the is operator returns  To summarize and complement the existing answers: python.exe is a console (terminal) application for launching CLI-type scripts. Unless run from an existing console window, python.exe opens a new console window. Standard streams sys.stdin, sys.stdout and sys.stderr are connected to the console window.

Python difference between is and , While on the other hand == checks if the values of two operands are equal or not. If yes, the condition becomes true and it returns a non zero  Difference between == and = in Python In Python and many other programming languages, a single equal mark is used to assign a value to a variable, whereas two consecutive equal marks is used to check whether 2 expressions give the same value.

What is the difference between = and == in Python ?, Difference between two sets in Python is equal to the difference between the number of elements in two sets. The function difference() returns a set that is the difference between two sets. Let’s try to find out what will be the difference between two sets A and B.

Comments
  • append if for a single item. maybe you mean extend.
  • For the more interesting case of += vs extend: stackoverflow.com/questions/3653298/…
  • += vs append stackoverflow.com/q/252703/6674599
  • +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.
  • 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].
  • 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 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 yup! But it's easy to be mistaken unless you already know this. A little additional precision has never hurt anyone, right?
  • There is difference between append and +=.
  • 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?
  • There's a difference because an augmented assignment introduces rebinding (explanation in my answer).
  • Voting this up because this is an important distinction between the two. Good work.
  • 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.
  • still, the += tests in that page uses += [one_var]. If we omit creating lists, += becomes the fastest option.