方括号是lists http://docs.python.org/tutorial/datastructures.html#more-on-lists而括号是tuples https://docs.python.org/tutorial/datastructures.html#tuples-and-sequences.
列表是可变的,这意味着您可以更改其内容:
>>> x = [1,2]
>>> x.append(3)
>>> x
[1, 2, 3]
而元组则不是:
>>> x = (1,2)
>>> x
(1, 2)
>>> x.append(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'
另一个主要区别是元组是可散列的,这意味着您可以将它用作字典的键等。例如:
>>> x = (1,2)
>>> y = [1,2]
>>> z = {}
>>> z[x] = 3
>>> z
{(1, 2): 3}
>>> z[y] = 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
请注意,正如许多人指出的那样,您可以将元组添加在一起。例如:
>>> x = (1,2)
>>> x += (3,)
>>> x
(1, 2, 3)
然而,这并不意味着元组是可变的。在上面的例子中,一个new元组是通过将两个元组作为参数相加来构造的。原始元组没有被修改。为了证明这一点,请考虑以下事项:
>>> x = (1,2)
>>> y = x
>>> x += (3,)
>>> x
(1, 2, 3)
>>> y
(1, 2)
然而,如果您要使用列表构建相同的示例,y
还将更新:
>>> x = [1, 2]
>>> y = x
>>> x += [3]
>>> x
[1, 2, 3]
>>> y
[1, 2, 3]