Python中方括号和括号括起来的列表有什么区别?

2022-01-19 00:00:00 python list tuples

问题描述

>>> x=[1,2]
>>> x[1]
2
>>> x=(1,2)
>>> x[1]
2

它们都有效吗?出于某种原因是首选吗?

Are they both valid? Is one preferred for some reason?


解决方案

方括号是 列表,而括号是元组.

Square brackets are lists while parentheses are tuples.

列表是可变的,这意味着您可以更改其内容:

A list is mutable, meaning you can change its contents:

>>> 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'

另一个主要区别是元组是可散列的,这意味着您可以将其用作字典的键等.例如:

The other main difference is that a tuple is hashable, meaning that you can use it as a key to a dictionary, among other things. For example:

>>> 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'

<小时>

请注意,正如许多人所指出的,您可以将元组添加在一起.例如:


Note that, as many people have pointed out, you can add tuples together. For example:

>>> x = (1,2)
>>> x += (3,)
>>> x
(1, 2, 3)

但是,这并不意味着元组是可变的.在上面的例子中,一个 new 元组是通过将两个元组加在一起作为参数来构造的.原始元组未修改.为了证明这一点,请考虑以下几点:

However, this does not mean tuples are mutable. In the example above, a new tuple is constructed by adding together the two tuples as arguments. The original tuple is not modified. To demonstrate this, consider the following:

>>> x = (1,2)
>>> y = x
>>> x += (3,)
>>> x
(1, 2, 3)
>>> y
(1, 2)

然而,如果你用一个列表来构造这个相同的例子,y 也会被更新:

Whereas, if you were to construct this same example with a list, y would also be updated:

>>> x = [1, 2]
>>> y = x
>>> x += [3]
>>> x
[1, 2, 3]
>>> y
[1, 2, 3]

相关文章