Changing array variable changes another variable

Question:

In python, when I append to the "sim" variable the "history" variable changes.

history = [[[1],[2],[3],[4],[5]]]
sim = list(history[0])

sim[0].append(5)

Result: [[[1, 5], [2], [3], [4], [5]]]

How do I fix this? Thank you for your help!

Asked By: prince888

||

Answers:

From the built-in copy module’s docs:

Assignment statements in Python do not copy objects, they create
bindings between a target and an object. For collections that are
mutable or contain mutable items, a copy is sometimes needed so one
can change one copy without changing the other. This module provides
generic shallow and deep copy operations (explained below).

Your code, specifically the line sim = list(history[0]) is making an assignment, not a copy of history[0]. It looks like you want a copy instead:

import copy

history = [[[1], [2], [3], [4], [5]]]
sim = copy.deepcopy(history[0])

sim[0].append(5)

print(f"history:t{history}")
print(f"sim:tt{sim}")

> history:  [[[1], [2], [3], [4], [5]]]
> sim:      [[1, 5], [2], [3], [4], [5]]

Note: using list() to make a copy of a list creates a shallow copy, meaning only the top level of items is copied – the references to the inner lists still point to the same place. You can verify this by replacing the copy.deepcopy() with a copy.copy() – you’ll get the same result as in the original post.

Answered By: Danielle M.
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.