1

I searched and found this thread from a guy asking how to clone a list in Python since just doing new_list = old_list simply copied the reference.

The thread says that new_list = list(old_list) works, but I have tried it out and when I edit new_list, old_list also changes.

Did something change or am I doing something wrong here?

  • Same behavior, doesn't copy the list –  Oct 19 '18 at 20:54
  • What's in the list? Is it other references? Your code won't make a deep copy. – Mark Oct 19 '18 at 20:54
  • The list has other lists inside. So it's doing a shallow copy. Is there a way to do this without including "copy" to deepcopy it? –  Oct 19 '18 at 20:56
  • So everything in python is an object. while `new_list = list(old_list)` creates a new list, the references to the objects of in old list is unchanged. When you modify the objects pointed by the references they will still change. – Kevin He Oct 19 '18 at 20:58
  • Makes sense, thank you –  Oct 19 '18 at 20:59
  • The thread you cited includes the caveat that, if your original list contains references to other objects, then you need a `deepcopy`. That appears to be your problem. – Prune Oct 19 '18 at 21:01

4 Answers4

0

You can also try copy.deepcopy

>>> a = [1,2,3]
>>> b = a
>>> b[1]
2
>>> b[0] = 'a'
>>> b
['a', 2, 3]
>>> a
['a', 2, 3]
>>> import copy
>>> c = copy.deepcopy(a)
>>> c[0] = 'pink'
>>> c
['pink', 2, 3]
>>> a
['a', 2, 3]
>>>
anon
  • 77
  • 2
  • I was trying to avoid importing things but if it's necessary I guess I'll use it –  Oct 19 '18 at 20:58
0

What it does copy is the references contained within the list, but not the objects those references point to.

Consider:

>>> l1 = [{}, {}]
>>> l2 = list(l1)

Now if I add another element to l1 it does not magically appear in l2:

>>> l1.append({})
>>> l1
[{}, {}, {}]
>>> l2
[{}, {}]

However, if I modify the contents of one of the object in l1, the corresponding object in l2 also changes:

>>> l1[0]['key1'] = 'value1'
>>> l1
[{'key1': 'value1'}, {}, {}]
>>> l2
[{'key1': 'value1'}, {}]

What you want is copy.deepcopy().

NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

Observe the following:

old_list = [1, 2, 3, 4]

new_list = old_list

old_list[3] = 10

Yields:

[1, 2, 3, 10]
[1, 2, 3, 10]

Instead, you can do the following:

old_list = [1, 2, 3, 4]

new_list = old_list[:]

old_list[3] = 5

Yields:

[1, 2, 3, 4]
[1, 2, 3, 5]
rahlf23
  • 8,869
  • 4
  • 24
  • 54
0

You can use

new_list = copy.deepcopy(old_list)
pxe
  • 155
  • 7