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.
也就是說:第一個是性能方面會更好,在創建時就分配固定大小的內存,第二個就是字符串、數字為基本類型,相對其他數據類型,改變的情況要少。
python中的數據結構