A travel checklist receives another list of items from a coworker.
What You Need to Understand
append() adds its argument as one item; extend() adds each element of an iterable individually. Both mutate the existing list and return None.
When to Use It
A travel checklist receives another list of items from a coworker.
Step-by-Step Python Example
first = ["passport"]
second = ["passport"]
first.append(["charger", "cable"])
second.extend(["charger", "cable"])
print(first)
print(second)
How the Example Works
The appended list is nested; the extended list has three top-level strings.
Example Output
['passport', ['charger', 'cable']]
['passport', 'charger', 'cable']
['base', 'left', 'right']
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
parts = ["base"]
parts.extend(("left", "right"))
print(parts)
Important Behavior and Edge Cases
Extending with a string adds individual characters. Choose the intended shape before selecting a method.
Try It Yourself
Append and extend a tuple; compare the resulting lengths.
Common Beginner Mistakes
- Extending with a string adds individual characters. Choose the intended shape before selecting a method.
- Overlooking how an iterable is consumed, how element positions are chosen, or whether a function creates a new list.
Key Takeaways
append()adds its argument as one item;extend()adds each element of an iterable individually.- The appended list is nested; the extended list has three top-level strings.
- Extending with a string adds individual characters.