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

The contrast between them is dramatic

What’s the Difference Between Python’s .append and .extend List Methods?
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

The supplied argument in the .append method is treated as an element, which can be thought of as a single item. The implication is that you can expect the length of the list to be one greater than it was prior to the append.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

The supplied argument in the .extend method is treated as an iterable, which can be thought of as a collection of items. The implication is that you can expect the length of the list to be n items greater where n is the number of iterations for the given argument.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 iterablel = [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.

Subscribe to Dreams of Fortunes and Cookies

Sign up now to get access to the library of members-only issues.
Jamie Larson
Subscribe