Coming from other languages, I am a little bit confused about the way Python variable assignments in lists. As an example, let's say:
x = [4, 5, 2, 70, 1]
y = x
y.sort()
If x and y are printed, the result is the same for both variables:
x = [1, 2, 4, 5, 70]
y = [1, 2, 4, 5, 70]
I did not quite expect this behavior. I thought the sequence of x would not be changed, since I applied the sort method only on list y.
On the other hand, if I had assigned the contents of list x to list y using slicing operators, then I would achieve the expected (at least in my case) behavior:
x = [4, 5, 2, 70, 1]
y = x[:]
y.sort()
If x and y are printed, I see that list x remains untouched.
x = [4, 5, 2, 70, 1]
y = [1, 2, 4, 5, 70]
Can somebody explain the logic behind?
Thank you!