Compare shallow copies of a nested list

Type one expression at a time and check its delimiters. · 178 words

A nested list contains lists inside another list. A shallow copy duplicates only the outer container; inner lists remain shared. Start with scores = [[1, 2], [3, 4]] and make shallow = scores[:]. The slice gives shallow its own outer list, but both variables still refer to the same inner lists. Thus shallow[0][0] = 99 changes scores to [[99, 2], [3, 4]]. By contrast, shallow.append([5, 6]) changes only shallow, because it adds an item to the separate outer list. This distinction matters whenever an experiment saves a baseline and modifies a working result.

Compare two common shallow-copy forms with a different example. Let grid = [['a'], ['b']], then create slice_copy = grid[:] and method_copy = grid.copy(). Both outer lists are separate from grid, but both still share the inner lists. If slice_copy[0].append('x'), all three variables show ['a', 'x'] in their first inner list. A deep copy, made with copy.deepcopy, would also duplicate the inner lists, so it would not show this shared change. Shallow copying is quick, but safe only when nested mutable objects will not be edited.

Check your recall

After b = a[:] for a = [[1], [2]], what does b[0].append(9) do to a?

Check your answer

It changes a to [[1, 9], [2]]. The slice created a new outer list, but a[0] and b[0] still refer to the same inner list, so appending through b also changes the data seen through a.

Sources and credits

Original KeyTouch lesson. Background reading · Python Software Foundation · The Python Tutorial.