20

In Python, the only difference between a list and a tuple that I know of is "lists are mutable but tuples are not". But as far as I believe, it depends on whether the coder wants to risk mutability or not.

So I was wondering whether there are any cases where the use of a tuple over a list is a must. Things that can not be done with a list but can be done with a tuple?

4

3 回答 3

30

您可以将元组用作字典中的键并将元组插入集合中:

>>> {}[tuple()] = 1
>>> {}[list()] = 1 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

这基本上是 atuple是可散列的而 alist不是的结果:

>>> hash(list())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> hash(tuple())
3527539
于 2012-07-09T16:14:27.920 回答
13

@Otto 的回答非常好。我唯一要补充的是,当您打开第 3 方扩展程序时,您确实需要查阅文档。某些函数/方法可能需要一种或另一种数据类型(或根据您使用的数据类型而产生不同的结果)。一个例子是使用元组/列表来索引一个 numpy 数组:

import numpy as np
a=np.arange(50)
a[[1,4,8]] #array([1, 4, 8])
a[(1,4,8)] #IndexError

编辑

此外,快速计时测试表明创建元组比创建列表快得多:

import timeit
t=timeit.timeit('[1,2,3]',number=10000000)
print (t)
t=timeit.timeit('(1,2,3)',number=10000000)
print (t)

记住这一点很好。换句话说,做:

for num in (8, 15, 200):
    pass

代替:

for num in [8, 15, 200]:
    pass
于 2012-07-09T16:34:01.223 回答
4

此外,现在使用运算符的过时字符串格式%要求参数列表是一个元组。列表将被视为单个参数:

>>> "%s + %s" % [1, 2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> "%s + %s" % (1, 2)
'1 + 2'
于 2012-07-10T01:04:09.110 回答