Michael Joseph Michael Joseph - 25 days ago 7
Python Question

Confused about how the assignment operator works

There is something about the way python assigns a value to a variable that I'm not fully comprehending. Why is it that this:

charlie = ['d', 'o', 'p', 'e']
beth = charlie
beth[0] = charlie[1]
print charlie


gives me this:

['o', 'o', 'p', 'e']


As far as I understand the assignment operator only works one way, thus this code should only change the first index of beth, not charlie. So what gives?

Answer

When you say beth = charlie, beth is now an alias of charlie. That means that anything that happens to beth now happens to charlie.

http://gestaltrevision.be/wiki/python/aliases

In order for this not to happen, you can try beth = list(charlie) or beth = charlie[:].

Comments