What is the difference between plus and add in python for list manipulation?

Possible duplicate:
Python append () vs. operator + on the lists, why do they give different results?

What is the actual difference between "+" and "adding" for manipulating lists in Python?

+9
source share
5 answers

There are two main differences. Firstly, + closer in value 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] 

Another, more noticeable difference is that the methods work in place: extend actually looks like += - in fact it has exactly the same behavior as += , except that it can accept any iterative, and += can only accept another list.

+14
source

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

+7
source
 >>> 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] 
+3
source

Operation + adds array elements to the original array. The array.append operation inserts an array (or any object) at 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]] 

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

+1
source

+ is a binary operator that creates a new list created by combining two lists of operands. append is an instance method that adds one item to an existing list.

PS Did you mean extend ?

0
source

All Articles