PY-2

Copy Before Mutating

  • Easy
  • Mutation and Copying
  • Python

Task

Write append_to_copy(values, item). It must return a new list containing all items from values, followed by item. The original list must not change.

This problem concerns a shallow copy. The returned outer list is new, but the items already inside it are the same objects as the items inside values. If item is itself a list, it is appended as one item; its contents are not inserted separately. This problem does not require a deep copy.

Example

The two variables refer to different outer lists. Mutating the returned list afterward must therefore not add or remove items from values. The shallow-copy boundary matters for nested items:

The nested list is shared, so changing that child is visible through both outer lists. Only the outer list itself must be new; do not use this task to teach or implement deepcopy.

Your implementation

Edit solution.py and keep this function name and signature:

Return a list even when values is empty. Preserve the order of its existing items. Do not assign another name to the same list and mutate it. Do not change values at any point.