1

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?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Naz
  • 2,012
  • 1
  • 21
  • 45

3 Answers3

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