18

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>]
Community
  • 1
  • 1
Takkun
  • 8,119
  • 13
  • 38
  • 41

3 Answers3

17

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.

GreenMatt
  • 18,244
  • 7
  • 53
  • 79
8

This will work.

import copy
copy_list = copy.copy(original_list)

Also

copy_list = list(original_list)
elricL
  • 1,188
  • 3
  • 11
  • 20
1

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[:]
Artsiom Rudzenka
  • 27,895
  • 4
  • 34
  • 52