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

时间:2012-01-17 19:02:34

标签: python list

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

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

6 个答案:

答案 0 :(得分:228)

方括号为lists,括号为tuples

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

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

答案 1 :(得分:4)

它们不是列表,它们是列表和元组。您可以在Python教程中阅读tuples。虽然你可以改变列表,但是对于元组来说这是不可能的。

In [1]: x = (1, 2)

In [2]: x[0] = 3
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

/home/user/<ipython console> in <module>()

TypeError: 'tuple' object does not support item assignment

答案 2 :(得分:2)

第一个是列表,第二个是元组。列表是可变的,元组不是。

请查看本教程的Data Structures部分以及文档的Sequence Types部分。

答案 3 :(得分:2)

()括起的以逗号分隔的项目为tuple s,由[]括起的项目为list

答案 4 :(得分:2)

一个有趣的区别:

lst=[1]
print lst          // prints [1]
print type(lst)    // prints <type 'list'>

notATuple=(1)
print notATuple        // prints 1
print type(notATuple)  // prints <type 'int'>
                                         ^^ instead of tuple(expected)

即使元组只包含一个值,它也必须包含在元组中。例如(1,)代替(1)

答案 5 :(得分:1)

括号和括号的另一种不同之处是方括号可以描述列表理解,例如: [x for x in y]

而相应的括号语法指定元组生成器(x for x in y)

您可以使用:tuple(x for x in y)

获得元组理解

请参阅:Why is there no tuple comprehension in Python?

相关问题