What is the difference between append and extend for Python Lists?

This article shows the difference between append() and extend() for Python Lists.

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

🪁 Code faster with Kite, AI-powered autocomplete: Link *

✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link *

* These are affiliate links. By clicking on it you will not have any additional costs, instead you will support me and my project. Thank you! 🙏

Check out my Courses