Sorting lists in python issue -
i started learning python few days ago (with no prior programming experience nor knowledge) , stuck following thing not understand: let' have unsorted list "b" , want sort list "c" looks list "b":
b = [4,3,1,2] c=b c.sort() print b print c
what discovered both b , c sorted: [1,2,3,4] [1,2,3,4]
why so?
it seems solution works when create copy of "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 first solution not work?
thank you.
in first sample, copying b
c
reference, means whenever change (sorting, example) made on b
, applied on c
, because both point same object.
in second sample, copying array by value
, not by reference
, create entirely new object in memory. therefore, changes made on 1 of them not applied on other one.
Comments
Post a Comment