Reputation: 2072
When playing with a code I have noticed that [0,]*6
, does not return [0,0,0,0,0,0,]
but rather [0,0,0,0,0,0]
. Can you please explain why?
Upvotes: 1
Views: 161
Reputation: 384
Lists do not end with commas. It's just the way the syntax goes. However, Python will think the ('hello world')
to be a string. To make a tuple, you must end it with a comma ('hello world',)
. So, in your case, Python thought [0,]
to be equivalent to [0]
. It's just the way the syntax goes.
Upvotes: 1
Reputation: 5061
()
(,)
is different 1st shows value
and other is tuple
, while in case of list []
and [,]
both presentation is same.
In [4]: [0,]*6
Out[4]: [0, 0, 0, 0, 0, 0]
In [5]: [0]*6
Out[5]: [0, 0, 0, 0, 0, 0]
In [6]: (1,)*6
Out[6]: (1, 1, 1, 1, 1, 1)
In [7]: (1)*6
Out[7]: 6
In [8]: [0,] == [0]
Out[8]: True
In [9]: (0,) == (0)
Out[9]: False
Upvotes: 3
Reputation: 3215
[0,0,0,0,0,0,]
and [0,0,0,0,0,0]
are the same lists. Last comma is acceptable by python syntax analyzer in order to distinguish a variable and a tuple with a variable inside: (1)
is int
, (1,)
is tuple
.
Upvotes: 6