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? 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. Commented Aug 17, 2018 at 17:03
  • 1
    [*x] is legal syntax... But only in Python 3. 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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.