liveBook · Manning

Extend method

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

list.extend() is a Python list method that adds each element produced by an iterable to the end of the list.

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

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Defines the single-iterable contract and demonstrates list, iterator, and nested-list behavior.
Examples
Demonstrates a picnic list and constructs song verses from reversed gift slices.
What it assumes
Assumes basic Python lists and indexing while explaining iterables through list-based examples.
What you can do after
Build lists from iterable contents and distinguish flat extension from nested append() results.
How it connects
Connects extend() with append(), iterables, list slicing, reversed(), and str.join().

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.