简体   繁体   中英

Sorting lists in python issue

I started learning python few days ago (with no prior programming experience nor knowledge) and am currently stuck with the following thing I do not understand: Let' say I have an unsorted list "b" and I want to sort a list "c" which looks exactly like list "b":

b = [4,3,1,2]
c=b
c.sort()

print b
print c

What I discovered is that both b and c are sorted: [1,2,3,4] [1,2,3,4]

Why is that so?

It seems this solution works perfectly when I create a copy of the "b" list:

b = [4,3,1,2]
c=b[:]
c.sort()

print b
print c

Results in: [4,3,1,2] [1,2,3,4]

But why does the first solution not work?

Thank you.

You already seem to understand that c = b is different to c = b[:] . In the first case c references the same object as b . In the latter it references a copy of b .

So it shouldn't be surprising that since b.sort() sorts the list referenced by b , When you inspect c it is also sorted - because it's the same object

The usual way to decouple a sorted list from the original is

c = sorted(b)

Because in the first solution, b and c both point to the same object. The slicing in the second solution creates a new object with the same contents as the old.

In the first sample, you are copying b into c by reference, which means that whenever any change (sorting, for example) is made on b , it will be applied on c , because basically they both point to the same object.

In the second sample, you are copying the array by value , not by reference , which create an entirely new object in the memory. Therefore, any changes made on the one of them will not be applied on the other one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM