元组/列表之间的区别是什么?它们的优点/缺点是什么?


当前回答

前面已经提到,这种差异主要是语义上的:人们期望元组和列表表示不同的信息。但这不仅仅是一个指导方针;一些库实际上根据传递的内容表现不同。以NumPy为例(复制自另一篇文章,我要求更多的例子):

>>> import numpy as np
>>> a = np.arange(9).reshape(3,3)
>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> idx = (1,1)
>>> a[idx]
4
>>> idx = [1,1]
>>> a[idx]
array([[3, 4, 5],
       [3, 4, 5]])

关键是,虽然NumPy可能不是标准库的一部分,但它是一个主要的Python库,在NumPy中,列表和元组是完全不同的东西。

其他回答

换句话说,TUPLES用于存储一组元素,其中组的内容/成员不会改变,而list用于存储一组元素,其中组的成员可以改变。

例如,如果我想在一个变量中存储我的网络IP,最好使用一个元组,因为IP是固定的。my_ip =('192.168.0.15', 33,60)。但是,如果我想存储一组未来6个月我将访问的地方的IP,那么我应该使用LIST,因为我会不断更新和添加新的IP到组中。像这样

places_to_visit = [
    ('192.168.0.15', 33, 60), 
    ('192.168.0.22', 34, 60), 
    ('192.168.0.1', 34, 60), 
    ('192.168.0.2', 34, 60), 
    ('192.168.0.8', 34, 60), 
    ('192.168.0.11', 34, 60)
] 

从5.3的文档中引证的方向。元组和序列:

虽然元组可能看起来类似于列表,但它们通常用于不同的情况和不同的目的。元组是不可变的,通常包含不同的元素序列,可以通过解包(参见本节后面的内容)或索引(对于namedtuples,甚至可以通过属性访问)访问这些元素。列表是可变的,它们的元素通常是同构的,并通过遍历列表来访问。

list和tuple的区别

元组和列表在Python中看起来都是相似的序列类型。

Literal syntax We use parenthesis () to construct tuples and square brackets [ ] to get a new list. Also, we can use call of the appropriate type to get required structure — tuple or list. someTuple = (4,6) someList = [2,6] Mutability Tuples are immutable, while lists are mutable. This point is the base the for the following ones. Memory usage Due to mutability, you need more memory for lists and less memory for tuples. Extending You can add a new element to both tuples and lists with the only difference that the id of the tuple will be changed (i.e., we’ll have a new object). Hashing Tuples are hashable and lists are not. It means that you can use a tuple as a key in a dictionary. The list can't be used as a key in a dictionary, whereas a tuple can be used tup = (1,2) list_ = [1,2] c = {tup : 1} # ok c = {list_ : 1} # error Semantics This point is more about best practice. You should use tuples as heterogeneous data structures, while lists are homogenous sequences.

list的值可以随时更改,但元组的值不能更改。

优点和缺点取决于使用。如果你有这样一个你不想改变的数据,那么你应该使用tuple,否则list是最好的选择。

列表是同构序列,而元组是异构数据结构。