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,123
  • 1
  • 24
  • 30
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
  • 620
  • 6
  • 15
0

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

ofrommel
  • 1,973
  • 13
  • 18
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
  • 6,633
  • 9
  • 33
  • 55