Question
Asked By – ooboo
Why do these two operations (append()
resp. +
) give different results?
>>> c = [1, 2, 3]
>>> c
[1, 2, 3]
>>> c += c
>>> c
[1, 2, 3, 1, 2, 3]
>>> c = [1, 2, 3]
>>> c.append(c)
>>> c
[1, 2, 3, [...]]
>>>
In the last case there’s actually an infinite recursion. c[-1]
and c
are the same. Why is it different with the +
operation?
Now we will see solution for issue: Python append() vs. + operator on lists, why do these give different results?
Answer
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.
This question is answered By – Abel
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0