开发者

lists in python, with references [duplicate]

This questio开发者_如何学运维n already has answers here: How do I clone a list so that it doesn't change unexpectedly after assignment? (23 answers) Closed 4 years ago.

How do I copy the contents of a list and not just a reference to the list in Python?


Look at the copy module, and notice the difference between shallow and deep copies:

The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):

  • A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

  • A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.


Use a slice notation.

newlist = oldlist

This will assign a second name to the same list

newlist = oldlist[:]

This will duplicate each element of oldlist into a complete new list called newlist


in addition to the slice notation mentioned by Lizard,

you can use list()

newlist = list(oldlist)

or copy

import copy
newlist = copy.copy(oldlist)


The answes by Lizard and gnibbler are correct, though I'd like to add that all these ways give a shallow copy, i.e.:

l = [[]]
l2 = l[:] // or list(l) or copy.copy(l)
l2[0].append(1)
assert l[0] == [1]

For a deep copy, you need copy.deepcopy().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜