What is the difference between append and extend for Python Lists?
This article shows the difference between append() and extend() for Python Lists.
This article shows the difference between append()
and extend()
for Python Lists.
#more
append(x)
¶
Appends x to the end of the sequence. This means it inserts one item. In the following example we have a nested list as the third item as a consequence.
a = [1, 2]
b = [3, 4]
a.append(b)
# a = [1, 2, [3, 4]]
extend(iterable)
¶
Extends the list by appending elements from the iterable.
a = [1, 2]
b = [3, 4]
a.extend(b)
# a = [1, 2, 3, 4]
For example, b could also be a tuple. This works and the resulting list would be the same. It's worth mentioning that the += operator does the same as .extend()
.
a = [1, 2]
b = (3, 4)
a += b
# a = [1, 2, 3, 4]
On the other hand, the single + operator with a new assignement is not allowed for different types:
a = [1, 2]
b = (3, 4)
a = a + b
# TypeError: can only concatenate list (not "tuple") to list
FREE VS Code / PyCharm Extensions I Use
✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link*
Python Problem-Solving Bootcamp
🚀 Solve 42 programming puzzles over the course of 21 days: Link*