What is the difference between Python’s list methods append() and extend()?
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
- Syntax and Usage Patterns
- Performance Considerations
- Practical Examples
- Common Use Cases
- When to Use Each Method
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.
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.
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 objectxto the end of the listlist.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.
# 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:
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 complexityextend(): 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.
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
# 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
# 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
# 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
# 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
# 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
# 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
# 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:
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
- Python Documentation - Lists
- Real Python - Lists and Tuples in Python
- Python Glossary - Mutable
- GeeksforGeeks - Python List append() vs extend()
- 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.