PythonPython ListsAppend versus extend

What is the difference between `append()` and `extend()`?

Question 81 of 88 · Updated

On this page

append() adds its argument as one item; extend() adds each item from an iterable separately. Both modify the original list and return None.

Example: Add groceries#

Imagine you already have milk on your shopping list and want to add bread and eggs.

PYTHON
extras = ['bread', 'eggs'] a = ['milk'] a.append(extras) print(a) # ['milk', ['bread', 'eggs']] b = ['milk'] b.extend(extras) print(b) # ['milk', 'bread', 'eggs']

With append(), the entire extras list becomes one nested item. With extend(), its two elements become separate items in the destination list.

Quick comparison#

Featureappend()extend()
AcceptsAny single objectAn iterable (list, tuple, string, etc.)
AddsExactly one itemEach item from the iterable
Changes original listYesYes
Return valueNoneNone
Typical useAdd one recordCombine batches of records

Watch out for strings#

Starting with an empty list, append('hi') produces ['hi'], while extend('hi') produces ['h', 'i']. Strings are iterable, so extend() adds their characters individually.

Similarly, extend(5) raises TypeError because an integer is not iterable, but append(5) works.

Which should you use?#

Use append() to add a single student record, and extend() to add a batch of student records. Neither method recursively flattens nested lists.

Try it: Starting with an empty list, what happens when you call extend([])? Nothing is added. Calling append([]) instead produces [[]].

Interview takeaway: append() adds one object (amortized O(1) in CPython); extend() consumes an iterable, adding k elements in amortized O(k) time for ordinary bounded-cost iteration.

Official references#

References

  1. 1.
  2. 2.
    Mutable sequence typesdocs.python.org

Related questions

Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design