简体   繁体   English

在Python中带有方括号且没有方括号的列表

[英]List with square bracket and no brackets in Python

I want to know whether both of these are a list or not. 我想知道这两个都是列表。 In python, are both of these lists? 在python中,这两个列表都是吗?

x = [1,2,3]
## and
y = 1,2,3

Is y a list? y列表?

x is a list, but y is a tuple . x是一个列表,但是y是一个元组 The parentheses to define a tuple are optional in most contexts; 在大多数情况下, 用于定义元组括号是可选的。 it is the comma that defines the value, really. 确实是值定义的逗号

You can test this yourself with the type() function : 您可以使用type()函数自己对此进行测试:

>>> x = [1,2,3]
>>> type(x)
<type 'list'>
>>> y = 1,2,3
>>> type(y)
<type 'tuple'>
>>> y
(1, 2, 3)

Tuples are immutable; 元组是不可变的; you can create one but then not alter the contents (add, remove or replace elements). 您可以创建一个,但不能更改其内容(添加,删除或替换元素)。

No. The first is a list and the second is a tuple: 不。第一个是列表,第二个是元组:

>>> x = [1,2,3]
>>> type(x)
<class 'list'>
>>> y = 1,2,3  # This is equivalent to doing:  y = (1,2,3)
>>> type(y)
<class 'tuple'>
>>>

As a note for the future, if you ever want to see the type of an object, you can use the type built-in as I demonstrated above. 作为将来的说明,如果您想查看对象的类型,可以使用上面演示的内置type

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM