prince888
prince888

Reputation: 63

Changing array variable changes another variable

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!

Upvotes: 0

Views: 120

Answers (1)

Danielle M.
Danielle M.

Reputation: 3672

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:\t\t{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.

Upvotes: 1

Related Questions