Managing List Memory in Python

I can't figure out what the following behavior looks like in python:

x = [0, [1,2,3,4,5],[6]]
y = list(x)
y[0] = 10
y[2][0] = 7
print x
print y

It outputs:

[0, [1, 2, 3, 4, 5], [7]]
[10, [1, 2, 3, 4, 5], [7]]

Why is the second index x and y updated and only the first index y?

+4
source share
2 answers

This is because it list(x)creates a shallow copy of the list x. Some of the items xare lists. No copies are made for them; instead, they are passed as links. Thus, xthey yend with a link to the same list as the element.

If you want to create a deep copy of x (for example, to copy subscriptions), use:

import copy
y = copy.deepcopy(x)
+6
source

Python , . (, Unicode, Tuples) Python . (, Byte Arrays), Python .

, x, y , .

0

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


All Articles