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 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 Python's list methods append and extend?
append
appends a specified object at the end of the list:
>>> x = [1, 2, 3]
>>> x.append([4, 5])
>>> print(x)
[1, 2, 3, [4, 5]]
extend
extends the list by appending elements from the specified iterable:
>>> x = [1, 2, 3]
>>> x.extend([4, 5])
>>> print(x)
[1, 2, 3, 4, 5]
What is the difference between append and + in python?
The strange behavior you can see with your example is not due to the difference between the + operator and the append function.
It is due to the fact that you assigned a list as a default value to a function parameter and you assign the result of a concatenation in a local variable in g
.
That is not so widely known but defining a list (or a dict or an object) as a parameter default value is probably not what you want. When you do so, the list used as default value for the parameter is shared across all function calls.
So for the f
function:
- you call it a first time without the
L
parameter, the default value ([]
) is taken and appended with2
. So it becomes[2]
- you call it a second time without the
L
parameter, the default value is taken but it is now[2]
.2
is appended again and it becomes[2, 2]
which is now the default value of your function.
for the g
function:
- as for the
f
function, the default value is an empty list, but this list is never modified. Actually the result ofL + [2]
is affected to a local variableL
and the default value of the function remains unchanged. So when you call the function again, the default value is always[]
. - As Klimenkomud said in his answer using the
+=
operator instead of a concatenation and an assignation actually modifies the default value of theL
parameter. If you do so, theg
function will behave like thef
function.
As a conclusion, using an empty list as a parameter default value is almost never what you want. Instead, you probably want this:
def f(a, L=None):
L = L or []
...
Python append() vs. + operator on lists, why do these give different results?
To explain "why":
The +
operation adds the array elements to the original array. The array.append
operation inserts the array (or any object) into the end of the original array, which results in a reference to self in that spot (hence the infinite recursion in your case with lists, though with arrays, you'd receive a type error).
The difference here is that the +
operation acts specific when you add an array (it's overloaded like others, see this chapter on sequences) by concatenating the element. The append
-method however does literally what you ask: append the object on the right-hand side that you give it (the array or any other object), instead of taking its elements.
An alternative
Use extend()
if you want to use a function that acts similar to the +
operator (as others have shown here as well). It's not wise to do the opposite: to try to mimic append
with the +
operator for lists (see my earlier link on why). More on lists below:
Lists
[edit] Several commenters have suggested that the question is about lists and not about arrays. The question has changed, though I should've included this earlier.
Most of the above about array
s also applies to lists:
- The
+
operator concatenates two lists together. The operator will return a new list object. List.append
does not append one list with another, but appends a single object (which here is alist
) at the end of your current list. Addingc
to itself, therefore, leads to infinite recursion.- As with arrays, you can use
List.extend
to add extend a list with another list (oriterable
). This will change your current list in situ, as opposed to+
, which returns a new list.
Little history
For fun, a little history: the birth of the array module in Python in February 1993. it might surprise you, but arrays were added way after sequences and lists came into existence.
The difference between '=' and 'append' in list in this example?
a = [1]
b = a
b = [1,2]
print(a)
When you do this, the value for b
is reassigned therefore losing the connection with a
.
a = [1]
b = a
b.append(2)
print(a)
But here, appending to b
means the same list in the memory is appended a value. Since a
and b
still refer to the same memory, printing a
results the same as b
since they two are just two different aliases for the list.
Python: understanding difference between append and extend
As others have pointed out, extend
takes an iterable (such as a list, tuple or string), and adds each element of the iterable to the list one at a time, while append
adds its argument to the end of the list as a single item. The key thing to note is that extend
is a more efficient version of calling append
multiple times.
a = [1,2]
b = [1,2]
a.extend([3, 4])
for x in [3, 4]:
b.append(x)
assert a == b
append
can take an iterable as its argument, but it treats it as a single object:
a = [1,2]
a.append([3,4])
assert a == [1, 2, [3, 4]] # not [1, 2, 3, 4]
Related Topics
Any Way to Modify Locals Dictionary
Tensorflow Only Running on 1/32 of the Training Data Provided
What Are the Most Common Python Docstring Formats
What Does -1 Mean in Numpy Reshape
How to Create Multiline Comments in Python
How to Print an Exception in Python
How to Create Test and Train Samples from One Dataframe with Pandas
Programmatically Saving Image to Django Imagefield
Relative Imports - Modulenotfounderror: No Module Named X
Ignore Python Multiple Return Value
Replacing Column Values in a Pandas Dataframe
Django Passing Custom Form Parameters to Formset
How to Overload _Init_ Method Based on Argument Type
How to Set Max_Retries for Requests.Request
Get the Key Corresponding to the Minimum Value Within a Dictionary
Python MySQLdb: Library Not Loaded: Libmysqlclient.18.Dylib
Why Is Python Setup.Py Saying Invalid Command 'Bdist_Wheel' on Travis Ci