18

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

What is the actual difference between "+" and "append" for list manipulation in Python?

Community
  • 1
  • 1
Bappy
  • 621
  • 1
  • 7
  • 16

5 Answers5

26

There are two major differences. The first is that + is closer in meaning to extend than to append:

>>> a = [1, 2, 3]
>>> a + 4
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    a + 4
TypeError: can only concatenate list (not "int") to list
>>> a + [4]
[1, 2, 3, 4]
>>> a.append([4])
>>> a
[1, 2, 3, [4]]
>>> a.extend([4])
>>> a
[1, 2, 3, [4], 4]

The other, more prominent, difference is that the methods work in-place: extend is actually like += - in fact, it has exactly the same behavior as += except that it can accept any iterable, while += can only take another list.

lvc
  • 34,233
  • 10
  • 73
  • 98
21

Using list.append modifies the list in place - its result is None. Using + creates a new list.

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
  • 1
    +1, this is important because lists are mutable. Using `+` you create a new list without changing the original one, and you should know whether you intend to change the original list or not. – Azim Jan 07 '22 at 18:32
4
>>> L1 = [1,2,3]
>>> L2 = [97,98,99]
>>>
>>> # Mutate L1 by appending more values:
>>> L1.append(4)
>>> L1
[1, 2, 3, 4]
>>>
>>> # Create a new list by adding L1 and L2 together
>>> L1 + L2
[1, 2, 3, 4, 97, 98, 99]
>>> # L1 and L2 are unchanged
>>> L1
[1, 2, 3, 4]
>>> L2
[97, 98, 99]
>>>
>>> # Mutate L2 by adding new values to it:
>>> L2 += [999]
>>> L2
[97, 98, 99, 999]
Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
1

+ is a binary operator that produces a new list resulting from a concatenation of two operand lists. append is an instance method that appends a single element to an existing list.

P.S. Did you mean extend?

Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
0

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.

[1, 2, 3] + [4, 5, 6] // [1, 2, 3, 4, 5, 6]

b = [1, 2, 3]
b.append([4, 5, 6]) // [1, 2, 3, [4, 5, 6]]

Take a look here: Python append() vs. + operator on lists, why do these give different results?

Community
  • 1
  • 1
user278064
  • 9,982
  • 1
  • 33
  • 46