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
extend() for Python Lists.
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]]
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
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*
PySaaS: The Pure Python SaaS Starter Kit
🚀 Build a software business faster with pure Python: Link*