If I have this Python code:
foo = [3, 5, 9]
bar = foo
bar.append(9)
print(foo)
It returns
[3, 5, 9, 9]
Which surely means that when I appended 9
to bar
, it also affected foo
. How do I make the variable bar
equal to foo
, but so that when I edit bar
, it does not effect foo
?
You are altering a mutable value, so you need to make an explicit copy:
bar = list(foo)
or
bar = foo[:]
When assigning to a name in Python, all you do is store a reference to the value. Without creating a copy of the list, both foo
and bar
referred to the same list.
For non-mutable values this is not a problem; you replace a reference to, say, a string to point to a different value instead.
But lists (and dict
and set
and instances of most classes) are mutable. You didn't change foo
, you changed the value foo
refers to. You did foo.append(9)
, which Python sees as:
foo
refers to..append
on that value. This returns a method on a list instance.9
. This alters the list.Python names themselves are nothing more than labels, pointing to actual values. You could see the values as balloons, the names as little paper tags, and assignment is the act of tying the labels to the balloons. bar = foo
created a second paper tag, that was tied to the exact same balloon.
See this older answer of mine where I push the balloon metaphor around some more.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With