3

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!

marillion
  • 10,618
  • 19
  • 48
  • 63
  • possible duplicate of [Python references](http://stackoverflow.com/questions/2797114/python-references) – Junuxx Nov 13 '12 at 00:04

1 Answers1

6

Slicing makes a copy whereas assignment points both labels to the same list instance. Sorting y sorts the list instance, which is the same instance pointed to by x. Alternatively, you could use y = sorted(x) to get the result you want.

Silas Ray
  • 25,682
  • 5
  • 48
  • 63