0

I am trying to print a unpacked iterable, or a string if said iterable is empty in Python 3.9 (also happens in 3.10), and I am getting some unexpected behavior. print is applying the star operator to the whole Iterable or str expression, regardless of parentheses:

>>> print(*[1, 2, 3] or 'my string', sep=' ')
1 2 3
>>> print(*[] or 'my string', sep=' ')
m y   s t r i n g
>>> 

I would have expected print(*[] or 'my string', sep=' ') to print my string.

The * operator definitely supports parentheses, for example:

>>> print(*([1, 2, 3] or 'my string'), sep=' ')
1 2 3
>>> print(*([] or 'my string'), sep=' ')
m y   s t r i n g
>>> 

In which case, the result would make sense. Is this expected behavior? If so, is it documented somewhere? If not, does anyone know if it has been addressed/plans exist to fix it in the next version of python?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 1
    seems expected, because if it did unpacking first, then for comparison it would really be comparing 3 unrelated values that can't be really expressed (maybe sth like `1 2 3` (without separators)) against a single value that is a string in this case. It has to first compare the values and return the first truthy value (because `or`), but 3 unpacked values seem to not be comparable – Matiiss Dec 29 '21 at 17:42
  • 1
    I agree with @Matiiss, but if you are trying to get your expected output you can do something like `print(*[] or ['my string'],sep=' ')`. – Nathan Roberts Dec 29 '21 at 17:46
  • [@Matiiss](https://stackoverflow.com/users/14531062/matiiss) edit: the first example in my question actually shows that the unpacked list has truthiness because it's printing the string when the list is empty – walkerfinlay Dec 30 '21 at 13:22

0 Answers0