A delivery manifest gets several new packages at once.
What You Need to Understand
list.extend(iterable) iterates through its argument and adds each element to the list. Unlike append(), it does not store the entire iterable as one new item.
When to Use It
A delivery manifest gets several new packages at once.
Step-by-Step Python Example
packages = ["A"]
packages.extend(["B", "C"])
print(packages)
packages.extend("XY")
print(packages)
How the Example Works
The first call adds B and C. Extending with a string adds its characters X and Y separately.
Example Output
['A', 'B', 'C']
['A', 'B', 'C', 'X', 'Y']
[1, 2, 3]
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
items = [1]
items.extend((2, 3))
print(items)
Important Behavior and Edge Cases
Be careful when extending with strings or dictionaries: you get characters or keys, not necessarily the items you intended.
Try It Yourself
Extend a checklist with a tuple of two tasks.
Common Beginner Mistakes
- Be careful when extending with strings or dictionaries: you get characters or keys, not necessarily the items you intended.
- Using the wrong collection method for this operation without checking whether it mutates the object, returns a result, or raises on missing data.
Key Takeaways
list.extend(iterable)iterates through its argument and adds each element to the list.- The first call adds B and C.
- Be careful when extending with strings or dictionaries: you get characters or keys, not necessarily the items you intended.