简体   繁体   English

Python中列表的内存管理

[英]Memory management of lists in Python

I can't seem to understand following behavior in python: 我似乎无法理解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? 为什么x和y的第二个索引更新,只有y的第一个索引?

This happens because list(x) creates a shallow copy of the list x . 发生这种情况是因为list(x)创建了列表x浅表副本。 Some of the elements in x are lists themselves. x中的一些元素本身就是列表。 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. 以这种方式, xy最终具有与元素相同的列表的引用。

If you want to create a deep copy of x (ie to also copy the sublists) use: 如果要创建x的深层副本 (即也要复制子列表),请使用:

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. 在Python中,序列被分为可变序列,可以在创建之后进行更改,以及不可变序列。对于不可变序列(字符串,Unicode,元组),Python为它们制作副本。对于可变序列(列表,字节数组) ,Python为它们提供了参考。

So if you change x ,y will also be changed as as they have a reference to the same list. 因此,如果您更改x,y也将更改,因为它们具有对同一列表的引用。

The standard type hierarchy 标准类型层次结构

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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