Michael Joseph Michael Joseph - 1 year ago 69
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 Source

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


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