← Back to Articles
Tutorial

Python List append() vs extend() - Key Differences Explained

Understanding the difference between append() and extend() methods in Python lists. Learn when to use each method with clear examples and avoid common mistakes.

📌 list append vs extend, python list methods, add to list python

Python lists offer multiple ways to add elements, with append() and extend() being the most commonly used. While they may seem similar, they serve fundamentally different purposes.

The append() method adds a single element to the end of a list. Importantly, it adds exactly one element - if you pass a list, the entire list becomes a single nested element.

The extend() method adds multiple elements from an iterable to the end of a list. It unpacks the iterable and adds each individual element, effectively merging two lists.

The key difference: append() preserves the structure of what you add, while extend() flattens it. Think of append() as putting items in a box, and extend() as dumping the contents.

Performance-wise, extend() is generally faster when adding multiple elements because it avoids repeated function calls. However, for single items, append() is more readable and appropriate.

A common mistake is using append() when you want to merge lists, resulting in nested lists. Always use extend() (or += operator) when combining multiple lists.

Both methods modify the original list in-place and return None. This is a common gotcha - assigning the result of append() or extend() to a variable will lose your list.

The += operator works like extend() for lists, offering a more concise syntax for merging. However, be aware it creates a new list object in some contexts, unlike extend() which modifies in-place.

❌ Common Mistakes

Using append() to merge lists creates nested structures

Use extend() or += when combining lists

Assigning result of append() to a variable

Remember append() modifies in-place and returns None

Using extend() with a single non-iterable item

Use append() for single items like integers or strings

Code Examples

append() vs extend() - Visual Example

nums = [1, 2, 3]

# append() - adds as single element
nums.append([4, 5])
print(nums)  # [1, 2, 3, [4, 5]] - nested list!

# extend() - adds each element
nums = [1, 2, 3]
nums.extend([4, 5])
print(nums)  # [1, 2, 3, 4, 5] - flattened!

Common Pitfall - Return Value

my_list = [1, 2, 3]

# WRONG: append() returns None
result = my_list.append(4)
print(result)  # None
print(my_list)  # [1, 2, 3, 4]

# CORRECT: call method directly
my_list.append(5)
print(my_list)  # [1, 2, 3, 4, 5]

Performance Comparison

import timeit

# Multiple appends
list1 = []
for i in range(1000):
    list1.append(i)

# Single extend (faster)
list2 = []
list2.extend(range(1000))

# extend() is ~3x faster for multiple elements

Related Topics

More Python Tutorials