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]
python
Ethan Jackson

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[:]

Related Articles