list.extend() adds each element produced by one iterable to the end of an existing list. Passing a list therefore adds its individual items rather than nesting the list. section 3.3.2 section 13.3.1
Use extend() when:
- You need to add several items in one operation: items.extend(['chips', 'ice cream']). section 3.3.2
- You need to consume an iterator, such as reversed(gifts[:day]), and add its yielded elements. section 13.3.1
- Avoid append() for this job: append() adds its argument as one element, even when that argument is a list or iterator. section 13.3.1
Building verse lines
lines = ['On the third day of Christmas,', 'My true love gave to me,'] lines.extend(reversed(gifts[:3])) assert len(lines) == 5 The lines now contain the two opening lines followed by three gifts. Using append() instead would leave three elements, with the iterator or a converted list nested as the final element. section 13.3.1
