Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python append() vs. + operator on lists, why do these give different results?

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?

like image 572
ooboo Avatar asked Jan 07 '10 16:01

ooboo


People also ask

What is the difference between the append () and insert () list methods in Python?

The only difference between append() and insert() is that insert function allows us to add a specific element at a specified index of the list unlike append() where we can add the element only at end of the list.

How is append () different from extend () in list?

append() adds a single element to the end of the list while . extend() can add multiple individual elements to the end of the list.

What is the difference between appending a list and extending a list in Python?

What is the difference between the list methods append and extend? append adds its argument as a single element to the end of a list. The length of the list itself will increase by one. extend iterates over its argument adding each element to the list, extending the list.

What is the difference between append with list and concatenation with lists?

It is also important to realize that with append, the original list is simply modified. On the other hand, with concatenation, an entirely new list is created.


1 Answers

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

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

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.

like image 117
Abel Avatar answered Sep 27 '22 02:09

Abel