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


当前回答

列表是可变的;元组不是。

从docs.python.org/2/tutorial/datastructures.html

元组是不可变的,通常包含的异构序列 通过解包访问的元素(参见本节后面的内容) 或者索引(在命名元组的情况下甚至通过属性)。列表 是可变的,它们的元素通常是同质的和 通过遍历列表来访问。

其他回答

列表是可变的;元组不是。

从docs.python.org/2/tutorial/datastructures.html

元组是不可变的,通常包含的异构序列 通过解包访问的元素(参见本节后面的内容) 或者索引(在命名元组的情况下甚至通过属性)。列表 是可变的,它们的元素通常是同质的和 通过遍历列表来访问。

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.

前面已经提到,这种差异主要是语义上的:人们期望元组和列表表示不同的信息。但这不仅仅是一个指导方针;一些库实际上根据传递的内容表现不同。以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中,列表和元组是完全不同的东西。

关键的区别是元组是不可变的。这意味着一旦创建了元组,就不能更改其中的值。

因此,如果您需要更改值,请使用List。

元组的好处:

性能略有改善。 元组是不可变的,可以用作字典中的键。 如果你不能改变它,其他人也不能,也就是说你不需要担心任何API函数等改变你的元组没有被要求。

list和tuple的区别

Literal someTuple = (1,2) someList = [1,2] Size a = tuple(range(1000)) b = list(range(1000)) a.__sizeof__() # 8024 b.__sizeof__() # 9088 Due to the smaller size of a tuple operation, it becomes a bit faster, but not that much to mention about until you have a huge number of elements. Permitted operations b = [1,2] b[0] = 3 # [3, 2] a = (1,2) a[0] = 3 # Error That also means that you can't delete an element or sort a tuple. However, you could add a new element to both list and tuple with the only difference that since the tuple is immutable, you are not really adding an element but you are creating a new tuple, so the id of will change a = (1,2) b = [1,2] id(a) # 140230916716520 id(b) # 748527696 a += (3,) # (1, 2, 3) b += [3] # [1, 2, 3] id(a) # 140230916878160 id(b) # 748527696 Usage As a list is mutable, it can't be used as a key in a dictionary, whereas a tuple can be used. a = (1,2) b = [1,2] c = {a: 1} # OK c = {b: 1} # Error