In Python, append() and extend() are list methods for adding elements, but they behave very differently. Here's a breakdown:
1. append()
Purpose: Adds a single element to the end of the list.
Behavior:
Treats the argument as a single item, even if it’s a list or iterable.
Modifies the list in place (returns
None).
Example:
my_list = [1, 2, 3] my_list.append(4) # Add integer 4 print(my_list) # Output: [1, 2, 3, 4] my_list.append([5, 6]) # Add the entire list [5,6] as one element print(my_list) # Output: [1, 2, 3, 4, [5, 6]]
2. extend()
Purpose: Adds all elements of an iterable (e.g., list, tuple, string) to the end of the list.
Behavior:
Unpacks the iterable and appends each element individually.
Modifies the list in place (returns
None).
Example:
my_list = [1, 2, 3] my_list.extend([4, 5]) # Add elements 4 and 5 print(my_list) # Output: [1, 2, 3, 4, 5] my_list.extend("abc") # Add characters 'a', 'b', 'c' print(my_list) # Output: [1, 2, 3, 4, 5, 'a', 'b', 'c']
Key Differences
| Aspect | append() | extend() |
|---|---|---|
| Input | Accepts a single element. | Accepts an iterable (list, tuple, etc.). |
| Result | Adds the input as one item. | Adds each element of the iterable. |
| Nested Lists | Creates nested lists if used with iterables. | Flattens the iterable into the list. |
| Use Case | Add a single item (e.g., a number, string, or even a list as a nested element). | Merge two lists or add multiple items. |
Visual Comparison
Using append() with a List:
a = [1, 2] a.append([3, 4]) print(a) # Output: [1, 2, [3, 4]]
Using extend() with a List:
a = [1, 2] a.extend([3, 4]) print(a) # Output: [1, 2, 3, 4]
Common Mistakes
Mixing
append()andextend():my_list = [1, 2] my_list.append([3, 4]) # Adds [3,4] as one element → [1, 2, [3,4]] my_list.extend(5) # Error: extend() requires an iterable (e.g., [5])
When to Use Which
Use
append()to add a single element (e.g., a number, string, or object).Use
extend()to merge lists or add multiple elements from an iterable.
Bonus: Equivalent Operations
extend()can be mimicked with a loop:my_list = [1, 2] for item in [3, 4]: my_list.append(item) # Result: [1, 2, 3, 4]
extend()is similar to+=for lists:my_list += [3, 4] # Same as my_list.extend([3, 4])
Summary:
append()→ Add one item.extend()→ Add many items.
Comments
Post a Comment