Reputation: 169
Below is my code.
check = [[0] * 4] * 2
check[0][1] = 1
print(check)
check2 = [[0, 0, 0, 0], [0, 0, 0,0]]
check2[0][1] = 1
print(check2)
result:
[[0, 1, 0, 0], [0, 1, 0, 0]]
[[0, 1, 0, 0], [0, 0, 0, 0]]
I expect check
and check2
get same result but it is different.
why check[0][1]
and check[1][1]
are changed?? not only check[0][0]
Upvotes: 0
Views: 30
Reputation: 4779
check
is a shallow copy
check = [[0] * 4] * 2
- Creates only one list [0,0,0,0]
and rows 1 and 2 refer to this list.
So changing the elements of one row reflects changes in every other row.
To avoid such a scenario you can use a for-loop
to create the list like this
check = [[0 for _ in range(4)] for _ in range(2)]
Now, this will be a deep copy and not shallow copy.
check2
is a deep copy.
check2 = [[0, 0, 0, 0], [0, 0, 0,0]]
- Creates two separate lists [0,0,0,0]
. Row 1 and Row 2 refers to different copies of [0,0,0,0]
So changing the elements of one row will not reflect any changes in the other row.
Please read this SO answer to fully understand the concepts. https://stackoverflow.com/a/37830340
Upvotes: 2