Skip to content

How to Choose Between append() and extend() in Python

Learn when to use Python's append() (adds a single element) vs. extend() (unpacks iterables) to avoid nested lists or split strings in your code.

Both append() and extend() add elements to the end of a list, but they handle input data differently. Confusing them leads to unexpected nested structures or exploded strings.

How append() Works

The append() method treats input as a single object, adding it as one element:

nums = [1, 2]
nums.append(3)
print(nums)  # [1, 2, 3]

nums.append([4, 5])
print(nums)  # [1, 2, 3, [4, 5]] (a nested list!)

How extend() Works

The extend() method iterates over input and adds each element individually:

nums = [1, 2]
nums.extend([3, 4])
print(nums)  # [1, 2, 3, 4] (a flat list)

nums.extend([5])
print(nums)  # [1, 2, 3, 4, 5]

The String Pitfall

Since strings are iterable, extend() splits them into characters:

words = []
words.extend("Cat")
print(words)  # ['C', 'a', 't'] ❌

words = []
words.append("Cat")
print(words)  # ['Cat'] ✅

words.extend(["Dog", "Bird"])
print(words)  # ['Cat', 'Dog', 'Bird'] ✅

Output:

['C', 'a', 't']
['Cat']
['Cat', 'Dog', 'Bird']

Visual Comparison

data = [1, 2]

data.append([3, 4])

data = [1, 2]
data.extend([3, 4])

Quick Reference

Scenario Method Example
Add single value append() nums.append(5)
Add single string append() words.append("hello")
Merge two lists extend() list1.extend(list2)
Add from generator extend() nums.extend(range(5))

Summary

  • append(x): Adds x as a single element, regardless of type
  • extend(iterable): Unpacks the iterable and adds each element

When in doubt, ask yourself: "Do I want to add this thing, or add each item inside this thing?"

Navigation