-1

In the below code if I don't use comma then only one 0 gets printed while if I use comma 0 gets printed five times, why? Is it something to do with the immutable trait of the tuple?

 food = (0,) * 5  # comma used
 print (*food)

Output: 0 0 0 0 0

 food = (0) * 5  # comma not used
 print (*food)

Output:0

user2044296
  • 504
  • 1
  • 7
  • 18

4 Answers4

2

It's a syntax thing. What defines the tuple is not the parenthesis, but the presence of the comma:

  • Parenthesis around a single scalar expression are used to define order of evaluation: (1 + 2) * 3
  • A sequence of expressions separated by commas defines a tuple: 1, 2, 3.
    • This sequence can then be parenthesized if it needs to be embedded in some other expression: (1, 2, 3) * 5 is "the tuple (1,2,3) repeated five times".
  • Specifically for a single-item tuple, the syntax requires a trailing comma to differentiate it from a parenthesized expression: 0, is a tuple containing only the element 0; Usually you'd immediately want to parenthesize this expression if you wanted to embed it in a larger expression, e.g. (0,) * 5 ("the tuple consisting of zero, multiplied five times"). Whereas 0 and (0) both mean "the integer zero" (parenthesized in the latter form).
>>> type( (0, ) )
tuple

>>> type ( (0) )
int

So (0) * 5 is "the integer 0 multiplied by 5", giving you 0. There's no tuple involved at any point because the syntax you used does not define a tuple.

Avish
  • 4,516
  • 19
  • 28
1

Because:

>>> (0)
0
>>>

So 0 * 5 is 0, while:

>>> (0,)
(0,)
>>> 

Keeps it's type of a tuple.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
1

Tuples and Sequences From documentation a tuple with one item is constructed by following a value with a comma

A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective. For Example

>>> t=('hello')
>>> t
'hello'
>>> type(t)
<class 'str'>
>>> t1=('hello',)
>>> t1
('hello',)
>>> type(t1)
<class 'tuple'>
>>>
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
1

According to: [Python 3.Docs]: Built-in Types - class tuple([iterable]) (emphasis is mine):

  • Using a trailing comma for a singleton tuple: a, or (a,)

food definition (note that things would be the same without parentheses):

  • In the 1st case, it's a tuple (as (0,) is a tuple)
  • In the the 2nd case, it's a plain int (0 * 5)
>>> v0 = (0,)
>>> v1 = (0)
>>>
>>> v0, type(v0)
((0,), <class 'tuple'>)
>>> v1, type(v1)
(0, <class 'int'>)
>>>
>>> v0 * 5
(0, 0, 0, 0, 0)
>>> v1 * 5
0

Are you absolutely sure that print(*food) works (as you claim it does) in the 2nd case?

CristiFati
  • 38,250
  • 9
  • 50
  • 87