Differences between append() and extend() in Python
In Python, both append()
and extend()
methods are used to add elements to the end of a list, but they behave differently:
(1) append()
- It adds a single element to the end of the list.
- If you pass an iterable (like another list, tuple, or string) as an argument, it will add the entire iterable as a single element.
For example:
my_list = [1, 2, 3]
my_list.append([4, 5]) # Appends the entire list [4, 5] as a single element
print(my_list) # Output: [1, 2, 3, [4, 5]]
(2) extend()
- It adds all elements of an iterable (like another list, tuple, or string) to the end of the list.
- It iterates over the input iterable and adds each element individually to the list.
For example:
my_list = [1, 2, 3]
my_list.extend([4, 5]) # Adds elements 4 and 5 to the list
print(my_list) # Output: [1, 2, 3, 4, 5]
my_list.extend("abc") # Adds each character of the string "abc" as separate elements
print(my_list) # Output: [1, 2, 3, 4, 5, 'a', 'b', 'c']
Python append() vs extend()
Here is a table summarizing the differences between append()
and extend()
methods:
Aspect | append() | extend() |
Purpose | Adds a single element to the end of the list. | Adds all elements of an iterable individually to the list. |
Behavior with iterables | Adds the entire iterable as a single element. | Adds each item from the iterable individually to the list. |
Example with list | my_list = [1, 2, 3] my_list.append([4, 5]) Result: [1, 2, 3, [4, 5]] | my_list = [1, 2, 3] my_list.extend([4, 5]) Result: [1, 2, 3, 4, 5] |
Example with string | my_list = [1, 2, 3] my_list.append(“abc”) Result: [1, 2, 3, ‘abc’] | my_list = [1, 2, 3] my_list.extend(“abc”) Result: [1, 2, 3, ‘a’, ‘b’, ‘c’] |
When to use | When you want to add a single item (even if it is an iterable). | When you want to merge elements from one list (or iterable) into another. |