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?
Asked
Active
Viewed 103 times
1
-
just give enter after `[0,]` in idle. It would print `[0]` – Avinash Raj Sep 03 '15 at 09:10
-
They're the same. The last comma is redundant. – khelwood Sep 03 '15 at 09:12
-
possible duplicate of [Why does Python allow a trailing comma in list?](http://stackoverflow.com/questions/11597901/why-does-python-allow-a-trailing-comma-in-list) – moooeeeep Sep 03 '15 at 09:16
3 Answers
6
[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
.

u354356007
- 3,205
- 15
- 25
3
()
(,)
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

Vishnu Upadhyay
- 5,043
- 1
- 13
- 24
1
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.

Jordan A.
- 384
- 1
- 4
- 17