Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 remove 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>]
like image 271
Takkun Avatar asked Jul 07 '11 15:07

Takkun


People also ask

How do you copy a list without changing in Python?

Python List Copy() function does not change the original list is unchanged when the new list is modified. It is called a shallow copy.


1 Answers

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.

like image 80
GreenMatt Avatar answered Oct 22 '22 22:10

GreenMatt