简体   繁体   English

Python可变/不可变容器

[英]Python mutable/immutable containers

Are the following containers mutable or immutable in Python? 以下容器在Python中是可变的还是不可变的?

  • List 清单

  • Tuple 元组

  • Dictionary 字典

List, Dictionary: Mutable 列表,字典:可变

Tuple: Immutable 元组:不可变

tuple - immutable

list- mutable

dictionary - mutable

Mutable means value of a variable can be changed in the same memory block itself where the variable is stored or referenced. 变量的可变均值可以在存储或引用该变量的同一存储块本身中更改。

Immutable means, when you try to change the value of a variable, it creates a new memory block and stores the new value over there. 不可变意味着,当您尝试更改变量的值时,它将创建一个新的内存块并将新值存储在该内存块中。

Immutable -- Strings, Tuples, Numbers etc Mutable -- Lists, Dictionaries, Classes etc 不可变-字符串,元组,数字等不可变-列表,字典,类等

Example: 例:

Let us consider a List, which is mutable... 让我们考虑一个可变的列表...

a=[1,2,3] suppose list 'a' is at a memory block named "A0XXX" now if you want to add 4,5 to the list... b=[4,5] append them both a +=b now a=[1,2,3,4,5] So, now final list 'a' is also stored at same memory block "A0XXX" a = [1,2,3]假设列表'a'现在位于名为“ A0XXX”的存储块中,如果您想将4,5添加到列表中... b = [4,5]都将它们都附加到+ = b现在a = [1,2,3,4,5]因此,现在最终列表'a'也存储在同一存储块“ A0XXX”中

As list is mutable, it is stored at the same memory block. 由于列表是可变的,因此将其存储在同一存储块中。

If it is immutable, final list 'a' will be stored at the some other memory block "B0XXX" So mutable objects can be changed and stored at the same memory block, when you try to do the same with the immutable objects, a new memory block is created to store the changed values. 如果它是不可变的,则最终列表“ a”将存储在其他某个存储块“ B0XXX”中,因此,当您尝试对不可变对象执行相同操作时,可以更改可变对象并将其存储在同一存储块中创建存储块以存储更改的值。

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

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