Reputation: 63
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
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
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