[Tutor] Keeping change-in-place vs. copy methods straight
Steven D'Aprano
steve at pearwood.info
Sun May 4 12:31:33 CEST 2014
On Sun, May 04, 2014 at 10:00:08AM +0100, Alan Gauld wrote:
> For the specific case of sort you can always use
> the sorted() function which does return a reference
> (not a copy!) to the sorted item.
sorted() does make a copy of the list:
py> a = [2, 5, 3, 4, 1]
py> sorted(a), a
([1, 2, 3, 4, 5], [2, 5, 3, 4, 1])
Perhaps you meant that it didn't copy the individual items inside the
list? If so, you were correct:
py> a = [ [5, 6], [1, 2], [7, 8], [3, 4] ]
py> b = sorted(a)
py> b[0].append(999)
py> a
[[5, 6], [1, 2, 999], [7, 8], [3, 4]]
If you want to make copies of the items, you can import the copy module
and use copy.deepcopy first.
--
Steven
More information about the Tutor
mailing list