开发者

How to make a copy of a list of objects not change when modifying the original list? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicates:

How to clone a list in python?

What is the best way to copy a list in Python?

original_list = [Object1(), Object2(), Object3()]
copy_list = original_list
original_list.pop()

If I r开发者_Python百科emove an object from the original list, how can I keep the copy list from changing as well?

Original List

[<Object.Object instance at 0x00EA29E0>, <Object.Object instance at 0x00EA2DC8>, <Object.Object instance at 0x00EA2EE0>]

Copy List after popping the original list (I want this to equal what is above)

[<Object.Object instance at 0x00EA29E0>, <Object.Object instance at 0x00EA2DC8>]


Use copy.deepcopy() for a deep copy:

import copy
copy_list = copy.deepcopy(original_list)

For a shallow copy use copy.copy():

import copy
copy_list = copy.copy(original_list)

or slice with no endpoints specified :

copy_list = original_list[:]

See the copy docs for an explanation about deep & shallow copies.


This will work.

import copy
copy_list = copy.copy(original_list)

Also

copy_list = list(original_list)


Use deepcopy

Return a deep copy of x.

from copy import deepcopy

original_list = [Object1(), Object2(), Object3()]
copy_list = deepcopy(original_list)
original_list.pop()

But note that slicing will work faster in your case:

copy_list = original_list[:]
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜