0

My Code is:

L = [1, 2, 3, 4]
L2 = L
L2[2] = 'a'
L

this gives me:

[1, 2, 'a', 4]

could someone explain me please when I worked with L2 why L have changed?

Sven
  • 153
  • 2
  • 17

1 Answers1

3

L and L2 refer to same memory location.

Take the following example of how to copy a list variable to another variable.

>> x = [1,2,3]
>>> id(x)
141910924
>>> y = x
>>> id(y)
141910924
>>> z = list(x)
>>> id(z)
141676844
>>> x.append(10)
>>> x
[1, 2, 3, 10]
>>> y
[1, 2, 3, 10]
>>> z
[1, 2, 3]

use copy and deepcopy when we want to assign list values to other variables e.g.

>>> import copy
>>> x = [1,2,3, [4,5]]
>>> y = copy.copy(x)
>>> id(x)
141913324
>>> id(y)
139369964
>>> x.append(10)
>>> x
[1, 2, 3, [4, 5], 10]
>>> y
[1, 2, 3, [4, 5]]
>>> x[3].append(20)
>>> x
[1, 2, 3, [4, 5, 20], 10]
>>> y
[1, 2, 3, [4, 5, 20]]
>>> z = copy.deepcopy(x)
>>> z
[1, 2, 3, [4, 5, 20], 10]
>>> x[3].append(50)
>>> x
[1, 2, 3, [4, 5, 20, 50], 10]
>>> z
[1, 2, 3, [4, 5, 20], 10]
Vivek Sable
  • 9,938
  • 3
  • 40
  • 56