0

I know that it expands function arguments, but if I try something like this in Python 2:

x = [1,2,3]
print *x # SyntaxError: invalid syntax
print [*x] # SyntaxError: invalid syntax

So it appears that I am missing something about what * exactly does?

5
  • python2 or python3?
    – eyllanesc
    Commented Aug 17, 2018 at 17:01
  • print is not a function in python 2, it's a statement. And a list literal isn't a function either.
    – Aran-Fey
    Commented Aug 17, 2018 at 17:03
  • 1
    [*x] is legal syntax... But only in Python 3.
    – Kevin
    Commented Aug 17, 2018 at 17:04
  • Python 2, edited original question. Commented Aug 17, 2018 at 17:05
  • Despite your terminal question mark, you are not actually asking a question? Commented Aug 17, 2018 at 17:07

1 Answer 1

3

The * operator, unpacks the elements from a sequence/iterable (for example, list or tuple) as positional arguments to a function

On python2, print is a statement and not a function. So import print function from future, so that you use * operator for unpacking a list elements as arguments

>>> from __future__ import print_function
>>> print (*x)
1 2 3

On python3, print is a function. So you can use * operator straight-away

>>> print (*x)
1 2 3

Not the answer you're looking for? Browse other questions tagged or ask your own question.