NeuroAgent

Python append() vs extend(): Complete Guide

Learn the key differences between Python's append() and extend() list methods. Discover when to use each method, performance considerations, and practical examples for effective list manipulation in Python.

Question

What is the difference between Python’s list methods append() and extend()?

NeuroAgent

The primary difference between Python’s append() and extend() list methods lies in how they add elements: append() adds a single element to the end of a list, while extend() adds all elements from an iterable to the end of a list. append() increases the list length by 1, whereas extend() increases the list length by the number of elements in the iterable being added.

Contents


Core Functionality Differences

The append() method adds a single element to the end of a list, treating the argument as a single item regardless of its type. When you pass a list to append(), it becomes a nested element rather than expanding its contents.

python
my_list = [1, 2, 3]
my_list.append([4, 5])
print(my_list)  # Output: [1, 2, 3, [4, 5]]

In contrast, the extend() method takes an iterable and adds each of its elements individually to the list. This effectively “unpacks” the iterable and extends the list with multiple elements.

python
my_list = [1, 2, 3]
my_list.extend([4, 5])
print(my_list)  # Output: [1, 2, 3, 4, 5]

According to the official Python documentation, append() is equivalent to list[len(list):] = [x], while extend() is equivalent to list[len(list):] = iterable.

Syntax and Usage Patterns

Both methods have the same basic syntax but different behaviors:

  • list.append(x): Adds the single object x to the end of the list
  • list.extend(iterable): Extends the list by appending all items from the iterable

The append() method can accept any type of object - strings, numbers, lists, dictionaries, or even custom objects. Each becomes a single element in the list.

python
# Appending different types
mixed_list = []
mixed_list.append(42)          # Number
mixed_list.append("hello")     # String
mixed_list.append([1, 2, 3])   # List
mixed_list.append({"key": "value"})  # Dictionary
print(mixed_list)
# Output: [42, 'hello', [1, 2, 3], {'key': 'value'}]

The extend() method requires an iterable and will raise a TypeError if you pass a non-iterable object:

python
numbers = [1, 2, 3]
numbers.extend([4, 5, 6])      # Works with list
print(numbers)                 # [1, 2, 3, 4, 5, 6]

numbers.extend("789")          # Works with string
print(numbers)                 # [1, 2, 3, 4, 5, 6, '7', '8', '9']

try:
    numbers.extend(123)        # TypeError: 'int' object is not iterable
except TypeError as e:
    print(f"Error: {e}")

Performance Considerations

When working with performance-sensitive code, understanding the time complexity of these operations is crucial:

  • append(): O(1) - Constant time complexity
  • extend(): O(k) - Linear time complexity where k is the number of elements in the iterable

As explained by Real Python, append() is generally faster for adding single elements because it doesn’t need to process multiple items. However, when adding multiple elements, extend() is more efficient than multiple append() calls.

python
import time

# Performance comparison
large_list = list(range(10000))

# Using append in a loop
start = time.time()
for i in range(1000):
    large_list.append(i)
append_time = time.time() - start

# Using extend
start = time.time()
large_list.extend(range(1000))
extend_time = time.time() - start

print(f"Append loop: {append_time:.6f} seconds")
print(f"Extend: {extend_time:.6f} seconds")

In most cases, extend() performs better when adding multiple elements from an iterable, while append() is optimal for single element additions.

Practical Examples

Building a List from User Input

python
# Using append for individual items
user_items = []
while True:
    item = input("Enter an item (or 'done' to finish): ")
    if item.lower() == 'done':
        break
    user_items.append(item)

print("Your items:", user_items)

# Using extend for bulk operations
more_items = input("Enter multiple items separated by spaces: ").split()
user_items.extend(more_items)
print("Updated items:", user_items)

Working with Collections

python
# Combining two lists
list1 = ['a', 'b', 'c']
list2 = ['d', 'e', 'f']

# Method 1: Extend
combined1 = list1.copy()
combined1.extend(list2)

# Method 2: Append (creates nested list)
combined2 = list1.copy()
combined2.append(list2)

print("Extended:", combined1)    # ['a', 'b', 'c', 'd', 'e', 'f']
print("Appended:", combined2)    # ['a', 'b', 'c', ['d', 'e', 'f']]

Processing Data

python
# Reading lines from a file
lines = []
with open('data.txt', 'r') as file:
    for line in file:
        lines.append(line.strip())  # Single line at a time

# Alternative approach using extend
lines = []
with open('data.txt', 'r') as file:
    lines.extend(file.readlines())  # All lines at once

Common Use Cases

When to Use append()

  • Adding individual elements to a list
  • Building lists incrementally in loops
  • Creating nested list structures
  • When you need to preserve the original structure of the data being added
python
# Building a list of dictionaries
users = []
user_data = [
    {"name": "Alice", "age": 30},
    {"name": "Bob", "age": 25},
    {"name": "Charlie", "age": 35}
]

for data in user_data:
    users.append(data)

# Creating nested lists
matrix = []
row1 = [1, 2, 3]
row2 = [4, 5, 6]
matrix.append(row1)
matrix.append(row2)
print(matrix)  # [[1, 2, 3], [4, 5, 6]]

When to Use extend()

  • Combining multiple lists
  • Adding elements from any iterable (strings, tuples, sets, generators)
  • Bulk operations when performance matters
  • When you want to flatten the contents of an iterable
python
# Combining collections
list1 = [1, 2, 3]
tuple_items = (4, 5, 6)
set_items = {7, 8, 9}
list1.extend(tuple_items)
list1.extend(set_items)
print(list1)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Working with generators
def generate_numbers(n):
    for i in range(n):
        yield i * 2

numbers = [1, 2, 3]
numbers.extend(generate_numbers(4))  # Adds 0, 2, 4, 6
print(numbers)  # [1, 2, 3, 0, 2, 4, 6]

When to Use Each Method

Choose append() when:

  • You need to add a single element to the list
  • You want to create nested list structures
  • You’re processing items one by one in a loop
  • You need to preserve the original data structure
python
# Example: Processing individual items
shopping_cart = []
products = ["apple", "banana", "orange"]

for product in products:
    shopping_cart.append(product)
    # Additional processing for each item

Choose extend() when:

  • You need to add multiple elements from an iterable
  • You’re combining two or more collections
  • Performance is critical for bulk operations
  • You want to avoid nested structures
python
# Example: Efficient bulk operations
def process_large_dataset(data_chunk):
    result = []
    for chunk in data_chunk:
        result.extend(chunk)  # More efficient than multiple appends
    return result

Understanding the Return Value

Both methods modify the list in-place and return None, which is a common source of bugs for Python beginners:

python
my_list = [1, 2, 3]
new_list = my_list.append(4)
print(new_list)    # None
print(my_list)     # [1, 2, 3, 4]

my_list = [1, 2, 3]
new_list = my_list.extend([4, 5])
print(new_list)    # None
print(my_list)     # [1, 2, 3, 4, 5]

This behavior is documented in the Python glossary, which explains that most methods that mutate objects return None to avoid confusion and prevent common programming errors.


Sources

  1. Python Documentation - Lists
  2. Real Python - Lists and Tuples in Python
  3. Python Glossary - Mutable
  4. GeeksforGeeks - Python List append() vs extend()
  5. Stack Overflow - Difference between append and extend

Conclusion

Understanding the difference between append() and extend() is fundamental to effective Python list manipulation. append() adds a single element as-is, potentially creating nested structures, while extend() unpacks iterables and adds each element individually. Choose append() for single additions and nested structures, and extend() for bulk operations and combining collections. Remember that both methods modify lists in-place and return None, which prevents common chaining errors. Mastering these methods will help you write more efficient and readable Python code when working with lists.