-3

Below is what I tested on IPython. The result of print(*(a,a)) is what I expected but not print(*(a)). I though print(*(a)) would give [1,2]. The background is that I have some function taking a list as an argument and this "unexpected" unpacking behavior caused errors of mismatch in argument numbers. I can work around it by using ([a]) as shown by the last print command. However, I think this inconsistent unpacking behavior is very unpythonic. Can someone explain it? Thanks.


In [82]: a=[1,2]                                                                                                                                                      

In [83]: print(*(a))                                                                                                                                                  
1 2

In [84]: print(*(a,a))                                                                                                                                                
[1, 2] [1, 2]

In [85]: print (*([a]))                                                                                                                                               
[1, 2]
Olvin Roght
  • 7,677
  • 2
  • 16
  • 35
Jack
  • 1
  • 1

1 Answers1

3

print(*(a)) is actually the same as print(*a).

Tuples of exactly one value need to be expressed with a single comma after the value, so the correct syntax would be:

print(*(a,))

This is well-documented:

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.


I'd assume the reason behind this is that ( and ) are used to enclose expressions. For instance, consider the following:

x = (2 + 4)

What should be the value of x in this case? Logically, the intuitive (and actual) response is 6, not a tuple. So why would (a) be any different?

(a) would simply yield ... a. The same way that (2 + 4) yields 2 + 4.

In order to still be able to create a tuple of one element, the use of comma is enforced to distinguish between these cases and prevent any ambiguity.

Matias Cicero
  • 25,439
  • 13
  • 82
  • 154