-1

When testing Python parameter list with a single argument, I found some weird behavior with print.

>>> def hi(*x):
...     print(x)
...
>>> hi()
()
>>> hi(1,2)
(1, 2)
>>> hi(1)
(1,)

Could any one explain to me what the last comma mean in hi(1)'s result (i.e. (1,))

svarog
  • 9,477
  • 4
  • 61
  • 77
Sang
  • 4,049
  • 3
  • 37
  • 47

1 Answers1

2

Actually the behavior is only a little bit "weird." :-)

Your parameter x is prefixed with a star, which means all the arguments you pass to the function will be "rolled up" into a single tuple, and x will be that tuple.

The value (1,) is the way Python writes a tuple of one value, to contrast it with (1), which would be the number 1.

Here is a more general case:

def f(x, *y):
    return "x is {} and y is {}".format(x, y)

Here are some runs:

>>> f(1)
'x is 1 and y is ()'
>>> f(1, 2)
'x is 1 and y is (2,)'   
>>> f(1, 2, 3)
'x is 1 and y is (2, 3)'
>>> f(1, 2, 3, 4)
'x is 1 and y is (2, 3, 4)'

Notice how the first argument goes to x and all subsequent arguments are packed into the tuple y. You might just have found the way Python represents tuples with 0 or 1 components a little weird, but it makes sense when you realize that (1) has to be a number and so there has to be some way to represent a single-element tuple. Python just uses the trailing comma as a convention, that's all.

Ray Toal
  • 86,166
  • 18
  • 182
  • 232
  • I accepted your answer because of the `single-element tuple printing convention` explanation. It will be very pleaseful if you could explain why `(1)` is interpreted as number `1` – Sang Nov 20 '16 at 22:45
  • 2
    Sure, in general parentheses don't change the meaning of an expression. For example you can say `4+(1)` and it will be 5, the same way `4*(2-1)` would be 4. Because the convention is to use parentheses for grouping of subexpressions, the designer of Python thought it would be too confusing to overload the meaning to mean both grouping and single-element tuples. Also Python has a `type` function. In fact `type((2))` is `int` and `type((2,))` is `tuple`. We don't want there to be any ambiguity, which there would be if `(2)` were treated as a tuple. – Ray Toal Nov 20 '16 at 23:00
  • Thanks very much for the detailed answer. I've just created [new answer](http://stackoverflow.com/questions/40710455/why-single-element-tuple-is-interpreted-as-that-element-in-python). Let me link the answer to your comment here – Sang Nov 20 '16 at 23:03