Pregunta

I have a problem understanding the process of argument unpacking from a list using the star operator in python.

I have followed the documentation entry and tried to re-create my own little example.

So I've defined a simple list of numbers:

list = [1, 2, 3]

and made a quick check, this works:

print(1, 2, 3)
(1, 2, 3)

and this (just for heads-up):

print([1, 2, 3])
[1, 2, 3]

On the other hand this bit fails:

print(*[1, 2, 3])
  File "<stdin>", line 1
    print(*[1, 2, 3])
          ^
SyntaxError: invalid syntax

And this also fails:

print(*list)
  File "<stdin>", line 1
    print(*list)
          ^
SyntaxError: invalid syntax

I made sure everything in the documentation works:

list = [1, 2]
range(*list)
[1]

And it did.

I'd like to understand how exactly argument unpacking from list works and what to expect from it, because it doesn't seem as straightforward as I thought.

¿Fue útil?

Solución

Unpacking only works when you are inside a function call:

>>> def foo(a,b,c):
...     pass
...
>>> foo(*[1,2,3])
>>>

Using it elsewhere will cause an Error:

>>> (*[1,2,3])
  File "<stdin>", line 1
    (*[1,2,3])
     ^
SyntaxError: invalid syntax

In Python 2.7, print is not a function, it is a statement. As far as the interpreter is concerned, this:

print(*[1,2,3])

Is syntactically equivalent to this:

print *[1,2,3]

Which is invalid. In Python 3.X, print is now a function, so unpacking will work.

>>> print(*[1,2,3])
1 2 3

You can port the functional print back to 2.7 by importing from the future:

>>> from __future__ import print_function
>>> print(*[1,2,3])
1 2 3

Otros consejos

change: print(\*[1, 2, 3]) to: print(*[1, 2, 3])

>>> print(*[1,2,3])
1 2 3

>>> print(\*[1,2,3])
  File "<stdin>", line 1
    print(\*[1,2,3])
                   ^
SyntaxError: unexpected character after line continuation character

it wont work for python2 print because its not a function. it will work for python 3. example:

>>> def x(a,b,c):
...     print(a,b,c)

>>> x(*[1,2,3])
(1, 2, 3)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top