Reputation: 483
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.
Upvotes: 2
Views: 123
Reputation: 304117
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)
Upvotes: 4
Reputation: 62854
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.
Upvotes: 0
Reputation: 798456
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.
Upvotes: 2