0

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?

2 Answers2

1

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

rassar
  • 5,412
  • 3
  • 25
  • 41
0

You just assigned the same list to two variables, so charlie and beth are the same object.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
jonzee
  • 1,600
  • 12
  • 20