Alex Rivera | Logout

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

Asked 2010-01-07T16:56:58.527
152

Why do these two operations 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 infinite recursion. c[-1] and c are the same. Why is it different with the + operation?

Edit
Report

1 Answer

34

The concatenation operator + is a binary infix operator which, when applied to lists, returns a new list containing all the elements of each of its two operands. The list.append() method is a mutator on list which appends its single object argument (in your specific example the list c) to the subject list. In your example this results in c appending a reference to itself (hence the infinite recursion).

An alternative to '+' concatenation

The list.extend() method is also a mutator method which concatenates its iterable argument with the subject list. Specifically, it appends each of the elements of the iterable in iteration order.

An aside

Being an operator, + returns the result of the expression as a new value. Being a non-chaining mutator method, list.extend() modifies the subject list in-place and returns nothing.

Arrays

I've added this due to the potential confusion which Abel's answer abov

answered 2013-07-03T03:35:40.893

Your Answer