简体   繁体   中英

Memory management of lists in Python

I can't seem to understand following behavior 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 second index of x and y updated and only the first index of y?

This happens because list(x) creates a shallow copy of the list x . Some of the elements in x are lists themselves. No copies are created for them; they are instead passed as references. In this way x and y end up having a reference to the same list as an element.

If you want to create a deep copy of x (ie to also copy the sublists) use:

import copy
y = copy.deepcopy(x)

In Python,sequence are divided into mutable sequence,which can be changed after they are created, and immutable sequence.For immutable sequences(string,Unicode,Tuples),Python make a copy for them.For mutable sequences(Lists,Byte Arrays), Python make a reference for them.

So if you change x ,y will also be changed as as they have a reference to the same list.

The standard type hierarchy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM