rchughtai
rchughtai

Reputation: 63

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?

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

Is y a list?

Upvotes: 0

Views: 1059

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121456

x is a list, but y is a tuple. 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:

>>> 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).

Upvotes: 6

user2555451
user2555451

Reputation:

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.

Upvotes: 4

Related Questions