What’s the Difference Between Python’s .append and .extend List Methods?

The contrast between them is dramatic

Jonathan Hsu
Oct 17 · 2 min read
Photo by David Clode on Unsplash

Lists are a mutable ordered data type in Python that hold multiple elements. The list data type has two methods .append() and .extend() that both take a single argument and add the data at the end of the existing list. So what’s the difference?


.append() Method

l = [1,2,3]
l.append("Hello"))
# [1,2,3,"Hello"]
l = [1,2,3]
l.append(4)
# [1,2,3,4]
l = [1,2,3]
l.append([4,5,6])
# [1,2,3,[4,5,6]]
l = [1,2,3]
l.append({"a":4,"b":5,"c":6})
# [1,2,3,{"a":4,"b":5,"c":6}]

In each example above, the initial list has three items and after the append the list has four. Notice that appending a list or a dictionary nests the item in the next index available.


.extend() Method

l = [1,2,3]
l.extend("Hello")
# [1, 2, 3, 'H', 'e', 'l', 'l', 'o']
l = [1,2,3]
l.extend(4)
# TypeError: 'int' object is not iterable
l = [1,2,3]
l.extend([4,5,6])
# [1, 2, 3, 4, 5, 6]
l = [1,2,3]
l.extend({"a":4,"b":5,"c":6})
# [1, 2, 3, 'a', 'b', 'c']

We see here that the results are dramatically different from using .append. When extending a string, each character is stored as its own item. Since numeric values are not iterable, when attempting to extend with the value 4 we receive a TypeError. Extending with another list effectively combines the two lists. Finally, when extending with a dictionary, notice that the dictionary’s keys are stored and not the values.

Better Programming

Advice for programmers.

Jonathan Hsu

Written by

I’m a black belt problem-solver (literally). I enjoy the taking on new challenges, building skills, and sharing what I’ve learned. 🥋

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade