Appending, Inserting, and Extending a List
Appending adds one item, inserting puts an item at a specified position, and extending draws items from an iterable.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Trace an element type
Starting with [1], appending [4, 5] results in [1, [4, 5]]. Extending with that list instead gives [1, 4, 5]. The difference is visible before considering performance. List mutability explains why all references to the original list can observe the operation.
Account for shifting
Inserting an item at the front of a Python list moves the following references right. Appending at the end can usually reuse spare capacity. Dynamic array growth explains why a single append sometimes needs a larger allocation.[1]
Follow the resulting length and shape
Starting with [3, 5], appending another list [8, 13] yields [3, 5, [8, 13]] with length three. Extending with those two values yields [3, 5, 8, 13] with length four. Inserting eight at position one yields [3, 8, 5] and shifts the suffix. Test shape as well as length because a nested list containing one value can give the same length as an extension by one value. See flattening nested sequences.
Distinguish updating a list from creating a new value
Python list mutation methods generally return None. The assignment items = items.append(8) mutates the object and then binds items to None, so a later list operation fails even though another alias can still observe the new item. Repeated insertion at the front of an array-backed list also shifts a long suffix on each call. When doing many efficient operations at both ends, consider the sequence-backed queue interface and test with realistic sizes.