Why does changing one variable that was assigned from a different variable change the variable it was assigned from? [duplicate]
![Why does changing one variable that was assigned from a different variable change the variable it was assigned from? [duplicate]](/_next/image?url=https%3A%2F%2Fcdn.sanity.io%2Fimages%2F80wy3gkl%2Fproduction%2F497db7c448a30b6bf2565bea31f7ffdee4651405-1280x720.png%3Fh%3D1000&w=3840&q=75)
I'm learning to use python, and found out that running the following code produces this output:
Code:
a = 'donkey'
b = 'horse'
c = [a, b]
d = c
print(c)
print(d)
d[0] = 'panda'
print(c)
print(d)
Output:
['donkey', 'horse']
['donkey', 'horse']
['panda', 'horse']
['panda', 'horse']
In other words, changing the variable d also changes the variable c, for some reason? Why does this happen? Is this an intended behavior, or just a quirk of Python?
note: I'm learning python 3, but I'm not sure if I need to use that tag or not. This is my first question on this site.
Answer
the operation
d = c
is not copying the content of c
to d
. It's pointing d
to the address of c
.
In order to copy the content of c
to d
, you need to do:
d = c[:]
Enjoyed this article?
Check out more content on our blog or follow us on social media.
Browse more articles