0
x = [[7, 8], 3, "hello", [6, 8], "world", 17] # List 1
w = list.copy(x) # copying list 1 to list 2
w[0][1] = 5 # changing the value in list 2
print(w)
print(x)

Output:

[[7, 5], 3, 'hello', [6, 8], 'world', 17]
[[7, 5], 3, 'hello', [6, 8], 'world', 17]

Changes to w are affecting x too.

gogaz
  • 2,323
  • 2
  • 23
  • 31
Pranab
  • 11
  • 1
  • 3
  • 1
    Please edit your question as it's unreadable – EdChum Feb 13 '18 at 11:41
  • 1
    in my understanding this is a duplicate of [shallow copy vs deep copy](https://stackoverflow.com/questions/17246693/what-exactly-is-the-difference-between-shallow-copy-deepcopy-and-normal-assignm) – Albin Paul Feb 13 '18 at 11:43
  • 5
    Possible duplicate of [What exactly is the difference between shallow copy, deepcopy and normal assignment operation?](https://stackoverflow.com/questions/17246693/what-exactly-is-the-difference-between-shallow-copy-deepcopy-and-normal-assignm) – Van Peer Feb 13 '18 at 11:48

3 Answers3

1
from copy import deepcopy
x = [[7, 8], 3, "hello", [6, 8], "world", 17]
w = deepcopy(x)

w[0][1] = 5 # changing the value in list 2
print(w)
print(x)

result:

[[7, 5], 3, 'hello', [6, 8], 'world', 17]
[[7, 8], 3, 'hello', [6, 8], 'world', 17]
Hasan Jafarov
  • 628
  • 6
  • 16
0

You need to use copy.deepcopy() because copy.copy() only copies the references of the elements in the list.

ofrommel
  • 2,129
  • 14
  • 19
0

deepcopy is the answer for your question :

>>> from copy import deepcopy
>>> x = [[7, 8], 3, "hello", [6, 8], "world", 17]
>>> x = [[7, 8], 3, "hello", [6, 8], "world", 17]
>>> w = deepcopy(x)
>>> w[0][1] = 5
>>> print(w)
[[7, 5], 3, 'hello', [6, 8], 'world', 17]
>>> print(x)
[[7, 8], 3, 'hello', [6, 8], 'world', 17]
Harsha Biyani
  • 7,049
  • 9
  • 37
  • 61