Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list assignment behavior in python

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!

like image 405
marillion Avatar asked Apr 26 '26 14:04

marillion


1 Answers

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.

like image 186
Silas Ray Avatar answered Apr 29 '26 03:04

Silas Ray



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!