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


当前回答

首先,它们都是Python中的非标量对象(也称为复合对象)。

元组,有序的元素序列(可以包含任何没有混叠问题的对象) 不可变(tuple, int, float, str) 使用+进行连接(当然会创建一个全新的元组) 索引 切片 Singleton(3,) # ->(3)而不是(3)# -> 3 List(其他语言中的数组),值的有序序列 可变的 单例[3] 克隆new_array = origin_array[:] 列表推导式[x**2 for x in range(1,7)]给出 [1,4,9,16,25,36](不可读)

使用list还可能导致别名错误(两条不同的路径 指向同一对象)。

其他回答

如果你去散步,你可以随时在(x,y)元组中记下你的坐标。

如果你想记录你的旅程,你可以每隔几秒钟将你的位置添加到一个列表中。

但你不能反过来做。

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

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

元组的好处:

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

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

从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.

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

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

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

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是对象,这些对象没有改变,但它所指向的内容。

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