Copying a Sequence with a Slice

A full slice of a Python list creates another outer list. Nested mutable values can still be shared.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace both containers
  2. Pick the result type intentionally
  3. Trace replacement and internal mutation independently
  4. Decide how much independence the operation promises

Trace both containers

After copying [[2], [9]] with a full slice, replacing the second outer entry changes only the copy. Appending through the first inner list changes the inner list observed from both sides. This is an example of a shallow container copy.

Pick the result type intentionally

A full slice of an immutable sequence need not give the caller an independently mutable object. If callers require a list, choose a list conversion explicitly. A function's postconditions can document whether modifying the result may affect the input.[1]

Trace replacement and internal mutation independently

For original = [[2], [5], [8]] and part = original[1:], changing part[0] to [99] affects only the outer copy. Starting again from the original slice, writing part[0][0] = 99 modifies the nested list shared with original position one. Compare both objects after each operation. This explains why an apparently independent extracted region can still change the source when elements are editable. See shallow container copies.

Decide how much independence the operation promises

If elements are immutable tuples containing only numbers, a list slice offers enough isolation for replacing whole entries. A saved editable table may need a copy of each row. Graph-like data can contain aliases and cycles, so a copying routine must decide whether to preserve shared structure. Test two positions pointing at the same row before and after copying. See input ownership in functions for making the promise visible to callers.

References

  1. Python Software Foundation, Python Standard Library: Built-in Types ↩