Duplicating a list item back to a list in Python

Copy item back to list:

>> a = [[1,2],[3,4]]
>> b = []
>> b = a[1]
>> a.insert(1,b)
>> a
[[1,2],[3,4],[3,4]]
>> a[2][0] = 0
>> a
???

What do you expect from list a? It looks like [[1,2], [0,4], [0,4]], which was very surprising for me, whereas I expected [[1,2], [1,4], [0, 4]]

I know the answer, but still the idea is not very clear. Please tell us in more detail why this happens and how to get rid of it.

+4
source share
2 answers
b = a[1]
a.insert(1,b)

bis a link to a[1], so when you change a link after inserting it, it appears in both places, since it essentially points to the same data.

if you want to avoid such a scenario, use deepcopy

from copy import deepcopy

a = [[1,2],[3,4]]
b = []
b = deepcopy(a[1])
a.insert(1,b)
print(a) # prints [[1, 2], [3, 4], [3, 4]]
a[2][0] = 0
print(a) # prints [[1, 2], [3, 4], [0, 4]]
+6
source

, python, " ". , , , , (). :

x = [1,2]
b = [1,3]
x[0] = b
b[0] = 2

x [[2,3], 2] [[1,3], 2].

, , 1 of a / b. 2 a. , 2 a, b , , 1.

+3

Source: https://habr.com/ru/post/1680985/


All Articles