Understand append() and extend() in Python lists

Append one object or extend a list with the items from an iterable, and distinguish in-place mutation from creating a new list.

Best practices
Python programming and application logging

append(value) adds one object to the end of a list. extend(iterable) adds each item yielded by an iterable. Both modify the existing list and return None.

Compare the results

fruits = ["apple", "banana"]
fruits.append(["grape", "orange"])
print(fruits)  # ['apple', 'banana', ['grape', 'orange']]

fruits = ["apple", "banana"]
fruits.extend(["grape", "orange"])
print(fruits)  # ['apple', 'banana', 'grape', 'orange']

Appending that inner list creates one additional element. Extending adds two elements; it does not recursively flatten arbitrary nesting.

Recognize iterable behavior

items = []
items.extend("abc")
print(items)  # ['a', 'b', 'c']

items.append("de")
print(items)  # ['a', 'b', 'c', 'de']

Strings yield characters; dictionaries yield keys; generators yield their produced values. extend() requires an iterable, while append() accepts any single object. If an iterator raises halfway through extension, already-added items can remain in the list.

Compare += and +

original = [1, 2]
alias = original
original += [3, 4]
print(alias)  # [1, 2, 3, 4]

combined = original + [5, 6]
print(original)  # [1, 2, 3, 4]
print(combined)  # [1, 2, 3, 4, 5, 6]

For lists, += extends in place, so other references observe the change. + creates a new list and requires another list operand. [ *first, *second ] also builds a new list from the two iterables. These are shallow operations: the elements themselves are not deep-copied.

Performance and clarity

A built-in list append is amortized constant time; extending necessarily processes the incoming items. Extending can avoid the overhead of a Python-level append loop, but do not treat that as a universal benchmark result for every iterable or implementation. Choose the operation that expresses the desired shape of the result.

FAQ

Can append take several arguments? No. append(1, 2) raises TypeError. Use extend([1, 2]), or append a tuple if the pair should be one item.

How is insert different? insert(index, value) inserts one object at a selected position, potentially shifting later elements. append() always targets the end.

Why did my variable become None? A statement such as items = items.append(value) assigns the method's return value. Call items.append(value) without reassigning it.

References

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting