If you want to add something to a list, use the append method:
list1 = []
list1.append(0)
If you want to append many items at once, use the extend method:
list1.extend([1, 2, 4, 8, 16, 32])
# That is the same as:
for obj in [1, 2, 4, 8, 16, 32]:
list1.append(obj)
# except faster and more convenient.
The extend method will accept any iterable object. That includes
sequences and containers like lists and tuples, iterators (you probably
haven’t learned about them yet!), strings and more.
Strings are iterable as a sequence of individual
characters, so list1.extend("hello")
will append each letter
separately:
list1.extend("hello")
# equivalent to:
for char in "hello":
list1.append(char)
List concatenation using the plus sign requires both arguments to be a
list, since otherwise it is not clear what sort of result you want:
# concatenate a list and a tuple
[0, 1, 2, 3] + (4, 5)
# concatenate a string and a list
"abcdef" + [0, 1, 2, 3]
Should they be a list or a tuple, and a string or a list?
List concatenation with the plus sign may also be inefficient, as it
always has to create a new list. For “adding” only two or three lists,
who cares? But if you add lots of lists, it gets very inefficient and
slow. If you add ten lists together like this:
a = [0] + [1] + [2] + [3] + [4] + [5] + [6] + [7] + [8] + [9]
the Python interpreter has to create nineteen lists and delete eighteen
of them to get the final result.
There has to be a better way, and that way is to use append or the
extend method. Both are in-place and don’t have to create new, temporary
lists and then delete them.
And that brings us to the +=
augmented assignment operator.
It might look like +
, but it is actually a different spelling of
list.extend. So these two lines of code are roughly equivalent:
list1 += obj
list1.extend(obj)
and they work pretty much identically.
Advantages:
-
can accept any iterable, not just another list;
-
appends items in place, so faster and more efficient.
Disadvantages:
- looks like a variant spelling of
+
but is actually extend
.