Both append() and extend() are used to add elements to a list in Python, but they work differently.
append() – Adds a Single Element (or Object)append() adds an element as a single item at the end of the list.my_list = [1, 2, 3]
my_list.append([4, 5]) # Appends the list as a single element
print(my_list) # Output: [1, 2, 3, [4, 5]]
* Used when you want to add a single element.
extend() – Merges Another Iterable :extend() takes an iterable (like another list, tuple, or set) and adds each element separately to the list.my_list = [1, 2, 3]
my_list.extend([4, 5]) # Adds elements separately
print(my_list) # Output: [1, 2, 3, 4, 5]
* Used when you want to add multiple elements individually.
| Feature | append() |
extend() |
|---|---|---|
| Adds as a single element? | Yes | No |
| Adds elements individually? | No | Yes |
| Accepts only iterables? | No (any object) | Yes (iterables only) |
| Example Input | my_list.append([4, 5]) |
my_list.extend([4, 5]) |
| Example Output | [1, 2, 3, [4, 5]] |
[1, 2, 3, 4, 5] |