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


当前回答

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

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

其他回答

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.

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

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

正如人们已经在这里回答的那样,元组是不可变的,而列表是可变的,但是使用元组有一个重要的方面我们必须记住

如果元组中包含列表或字典,即使元组本身是不可变的,也可以更改这些列表或字典。

例如,假设我们有一个元组,其中包含一个列表和一个字典为

my_tuple = (10,20,30,[40,50],{ 'a' : 10})

我们可以将列表的内容更改为

my_tuple[3][0] = 400
my_tuple[3][1] = 500

new tuple看起来像什么

(10, 20, 30, [400, 500], {'a': 10})

我们还可以更改tuple as内的字典

my_tuple[4]['a'] = 500

这将使整个元组看起来像

(10, 20, 30, [400, 500], {'a': 500})

发生这种情况是因为list和dictionary是对象,这些对象没有改变,但它所指向的内容。

因此,元组保持不变,没有任何异常

列表是可变的,元组是不可变的。 考虑一下这个例子。

a = ["1", "2", "ra", "sa"]    #list
b = ("1", "2", "ra", "sa")    #tuple

现在改变list和tuple的索引值。

a[2] = 1000
print a     #output : ['1', '2', 1000, 'sa']
b[2] = 1000
print b     #output : TypeError: 'tuple' object does not support item assignment.

因此证明下面的代码是无效的元组,因为我们试图更新一个元组,这是不允许的。

PEP 484——类型提示说元组元素的类型可以单独类型化;这样你就可以说Tuple[str, int, float];但是一个带有list类型类的列表只能接受一个类型参数:list [str],这暗示了两者的区别实际上是前者是异构的,而后者本质上是同构的。

此外,标准库通常使用tuple作为这些标准函数的返回值,而C将返回结构体。