Append vs Extend in Python List: Key Differences and Usage
append adds its argument as a single element to the end of a list, while extend adds each element of an iterable to the list individually. Use append to add one item and extend to merge another list or iterable into the original list.Quick Comparison
Here is a quick side-by-side comparison of append and extend methods for Python lists.
| Factor | append | extend |
|---|---|---|
| Purpose | Add a single element to the list | Add multiple elements from an iterable to the list |
| Argument Type | Any object | An iterable (like list, tuple, string) |
| Effect on List Length | Increases by 1 | Increases by number of elements in iterable |
| Nested List Result | Adds the whole object as one element | Adds elements individually, no nesting |
| Common Use Case | Add one item | Concatenate lists or add multiple items |
Key Differences
The append method adds its argument as a single element at the end of the list. This means if you append a list, the entire list becomes one nested element inside the original list.
In contrast, extend takes an iterable and adds each of its elements to the list one by one. It does not nest the iterable but merges its contents into the original list.
Because of this, append increases the list length by exactly one, while extend increases the length by the number of elements in the iterable. Also, append accepts any object, but extend requires an iterable like a list, tuple, or string.
Code Comparison
Using append to add a list to another list:
my_list = [1, 2, 3] my_list.append([4, 5]) print(my_list)
extend Equivalent
Using extend to add elements of a list to another list:
my_list = [1, 2, 3] my_list.extend([4, 5]) print(my_list)
When to Use Which
Choose append when you want to add a single item to the end of a list, including adding a list as one nested element.
Choose extend when you want to add multiple elements from another iterable to the list, effectively merging them.
Remember, append is for one item, extend is for many items.
Key Takeaways
append to add one item to a list, increasing length by one.extend to add all elements from an iterable, increasing length by that iterable's size.append nests the added object; extend merges elements individually.extend requires an iterable argument; append accepts any object.append for single additions and extend for combining lists.