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?
When append() method adds its argument as a single element to the end of a list, the length of the list itself will increase by one. Whereas extend() method iterates over its argument adding each element to the list, extending the list.
For a list, += is more like the extend method than like the append method. With a list to the left of the += operator, another list is needed to the right of the operator. All the items in the list to the right of the operator get added to the end of the list that is referenced to the left of the operator.
Append adds to the end of the list, while insert adds in front of a specified index.
The + operator creates a new list in python when 2 lists are combined using it, the original object is not modified. On the other hand, using methods like extend and append, we add the lists in place, ie, the original object is modified. Also using append inserts the list as a object while + just concatenates the 2 lists.
append is appending an element to a list. if you want to extend the list with the new list you need to use extend. Show activity on this post. Python lists are heterogeneous that is the elements in the same list can be any type of object. The expression: c.append (c) appends the object c what ever it may be to the list.
From the Python documentation: list.append (x) Add an item to the end of the list; equivalent to a [len (a):] = [x]. list.extend (L) Extend the list by appending all the items in the given list; equivalent to a [len (a):] = L. list.insert (i, x) Insert an item at a given position.
Whereas using + to combine the elements of lists (more than one element) in the existing list similar to the extend (as corrected by Flux ). So here the some_list2 and ["something"] are the two lists that are combined. This is wrong. += does not return a new list.
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.
Using list.append
modifies the list in place - its result is None
. Using + creates a new list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With