Understanding the difference between extend and append in python is essential for anyone who manipulates lists, as these two methods may look similar but serve distinct purposes. Choosing the wrong one can lead to nested lists, unexpected results, or performance issues in larger scripts. This guide explains how each method works, highlights their key differences, and provides practical examples to help you decide when to use append versus extend in your own code.
What is the append method?
The append method adds a single element to the end of a list. Regardless of the element's type—whether it is a number, string, tuple, or even another list—append treats it as one object and places it directly after the last existing item.
Syntax
list.append(element)
Behavior
- The original list is modified in place.
- The length of the list increases by exactly one.
- If the element itself is a list, that entire list becomes a single nested element inside the original list.
Example
numbers = [1, 2, 3]
numbers.append(4)
print(numbers) # Output: [1, 2, 3, 4]
letters = ['a', 'b']
letters.append(['c', 'd'])
print(letters) # Output: ['a', 'b', ['c', 'd']]
In the second example, the argument ['c', 'd'] is added as one item, resulting in a list whose third element is itself a list.
What is the extend method?
The extend method, on the other hand, iterates over an iterable argument and adds each of its items individually to the end of the list. It does not treat the argument as a single object; instead, it “extends” the list with the elements contained in the iterable It's one of those things that adds up. Turns out it matters..
Syntax
list.extend(iterable)
Behavior
- The original list is modified in place.
- The length of the list increases by the number of items in the iterable.
- If the argument is not iterable (e.g., an integer), a TypeError is raised.
Example
numbers = [1, 2, 3]
numbers.extend([4, 5])
print(numbers) # Output: [1, 2, 3, 4, 5]
letters = ['a', 'b']
letters.extend('cd')
print(letters) # Output: ['a', 'b', 'c', 'd']
Here, each element of the iterable ([4, 5] or the string 'cd') is appended separately, flattening the addition.
Key differences between extend and append in python
| Aspect | append | extend |
|---|---|---|
| What it adds | The whole argument as a single element | Each element of the argument individually |
| Argument type | Any object (including another list) | Must be an iterable (list, tuple, string, etc.) |
| Resulting length | Increases by 1 | Increases by len(iterable) |
| Nesting | Can create nested lists | Flattens the addition; no extra nesting level |
| Error on non‑iterable | No error (the object is stored as‑is) | Raises TypeError if argument is not iterable |
Understanding these distinctions helps avoid common bugs, such as unintentionally creating a list‑inside‑a‑list when you meant to merge two sequences The details matter here..
When to use append
Use append when you want to add one item to a collection, regardless of what that item is. Here's the thing — - Storing heterogeneous objects (e. In real terms, g. - Appending a computed result after each iteration of a loop. Consider this: typical scenarios include:
- Adding a user‑provided value to a log list. , a mix of numbers and dictionaries) where each object should remain a distinct entry.
Example: Building a list of squares
squares = []
for i in range(5):
squares.append(i * i)
print(squares) # [0, 1, 4, 9, 16]
Each iteration contributes a single integer, so append is the natural choice.
When to use extend
Choose extend when you need to merge another sequence into the existing list, preserving a flat structure. Still, common use cases are:
- Combining results from multiple function calls that return lists. - Expanding a list with values read from a file or user input. Practically speaking, - Concatenating static collections (e. g., adding default options to a user‑selected list).
Example: Merging two datasets
dataset_a = [10, 20, 30]
dataset_b = [40, 50]
dataset_a.extend(dataset_b)
print(dataset_a) # [10, 20, 30, 40, 50]
The resulting list contains all six numbers without any extra nesting.
Performance considerations
Both methods modify the list in place and have amortized O(1) time complexity for each element added. Still, there are subtle differences:
- append performs a single operation per call, making it slightly faster when adding one element. Plus, - extend must iterate over the supplied iterable, so its cost scales with the length of that iterable. If you are adding many elements one by one in a loop, using extend with a pre‑built list can be more efficient than repeated append calls.
Micro‑benchmark illustration (conceptual)
import time
# Using append in a loop
start = time.time()
lst = []
for i in range(100000):
lst.append(i)
print("append loop:", time.time() - start)
# Using extend with a pre‑built list
start = time.time()
lst = []
lst.extend(range(1
```python
00000))
print("extend:", time.time() - start)
In practice, the performance difference is negligible for small lists, but becomes noticeable when building large collections.
Summary
| Aspect | append | extend |
|---|---|---|
| Input type | Any object | Iterable |
| Effect on list | Adds one item | Adds multiple items |
| Resulting length | Increases by 1 | Increases by len(iterable) |
| Nesting | Can create nested lists | Flattens the addition |
| Error behavior | No error | Raises TypeError on non-iterable |
Choosing the right method depends on whether you want to add a single item or merge multiple items into your list. Use append for individual elements and extend for combining sequences. This distinction ensures cleaner code and prevents unintended nesting or runtime errors Easy to understand, harder to ignore..