In Python, the append() and extend() methods are used to add elements to a list, but they behave differently based on the type of argument provided:
1. list.append(item)
- Purpose: Adds a single element to the end of the list.
- Behavior:
- Treats the argument as a single object and inserts it into the list.
- If the argument is iterable (e.g., a list, tuple, or string), it adds the entire object as one element.
- Example:
a = [1, 2, 3]
a.append([4, 5]) # Adds the list [4, 5] as a single element
print(a) # Output: [1, 2, 3, [4, 5]]
2. list.extend(iterable)
- Purpose: Adds all elements of an iterable (e.g., list, tuple, string) to the end of the list.
- Behavior:
- Iterates over the argument and appends each element individually.
- Fails if the argument is not iterable (e.g., an integer or
None). - Example:
a = [1, 2, 3]
a.extend([4, 5]) # Adds 4 and 5 as separate elements
print(a) # Output: [1, 2, 3, 4, 5]
Key Differences
| Aspect | append() | extend() |
|---|---|---|
| Argument Type | Any single object (e.g., int, str, list). | Requires an iterable (e.g., list, tuple). |
| Result | Adds the object as one element. | Adds each item of the iterable. |
| Use Case | Insert a single item (even if it’s a list). | Merge elements of an iterable into the list. |
| Performance | O(1) time complexity. | O(k) time complexity (k = length of iterable). |
| Error Cases | None. Accepts any object. | Fails if the argument is not iterable (e.g., extend(5)). |
Examples to Clarify
Case 1: Adding a String
a = [1, 2]
a.append("hello") # Adds the string as a single element: [1, 2, "hello"]
a.extend("hello") # Adds each character: [1, 2, 'h', 'e', 'l', 'l', 'o']
Case 2: Adding a List
a = [1, 2]
a.append([3, 4]) # Result: [1, 2, [3, 4]]
a.extend([3, 4]) # Result: [1, 2, 3, 4]
Case 3: Non-Iterable Argument
a = [1, 2]
a.append(3) # Works: [1, 2, 3]
a.extend(3) # TypeError: 'int' is not iterable
When to Use Which?
- Use
append()to: - Add a single item (even if the item is a list).
- Preserve nested structures (e.g.,
[[4, 5]]instead of[4, 5]). - Use
extend()to: - Merge elements of an iterable into the list.
- Avoid nested lists when combining multiple elements.
Equivalent Operations
append()can be mimicked with:
a += [item] # Same as a.append(item)
extend()can be mimicked with:
a += iterable # Same as a.extend(iterable)
Performance Note
For large iterables, extend() is more efficient than repeatedly calling append() in a loop.
Example:
# Efficient
a.extend(range(1000))
# Inefficient
for i in range(1000):
a.append(i)
Choose append() for single elements and extend() for merging iterables!