python中的数据结构

变量将数据存储在内存中。这就意味着在创建变量时会在内存中开辟一个空间。基于变量的数据类型,解释器会分配指定内存,并决定什么数据可以被存储在内存中。

Python中的变量不需要声明变量的赋值操作既是变量声明和定义的过程。因此,每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建。

python中的数据结构主要包括:序列(如列表、元祖、字符串)、映射(如字典)、集合。

其中,序列中的元祖和字符串为不可变类型。原因,官方解释:

One is performance: knowing that a string is immutable means we can allocate space for it at creation time, and the storage requirements are fixed and unchanging. This is also one of the reasons for the distinction between tuples and lists.

Another advantage is that strings in Python are considered as “elemental” as numbers. No amount of activity will change the value 8 to anything else, and in Python, no amount of activity will change the string “eight” to anything else.

也就是说:第一个是性能方面会更好,在创建时就分配固定大小的内存,第二个就是字符串、数字为基本类型,相对其他数据类型,改变的情况要少。

原文地址:https://www.cnblogs.com/elena-shao/p/7121936.html