0
0
PythonComparisonBeginner · 3 min read

Append vs Extend in Python List: Key Differences and Usage

In Python, 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.

Factorappendextend
PurposeAdd a single element to the listAdd multiple elements from an iterable to the list
Argument TypeAny objectAn iterable (like list, tuple, string)
Effect on List LengthIncreases by 1Increases by number of elements in iterable
Nested List ResultAdds the whole object as one elementAdds elements individually, no nesting
Common Use CaseAdd one itemConcatenate 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:

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

extend Equivalent

Using extend to add elements of a list to another list:

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

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

Use append to add one item to a list, increasing length by one.
Use 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.
Pick append for single additions and extend for combining lists.