python argument unpacking puzzling behaviour -


i have problem understanding process of argument unpacking list using star operator in python.

i have followed documentation entry , tried re-create own little example.

so i've defined simple list of numbers:

list = [1, 2, 3] 

and made quick check, works:

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

and (just heads-up):

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

on other hand bit fails:

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

and fails:

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

i made sure in documentation works:

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

and did.

i'd understand how argument unpacking list works , expect it, because doesn't seem straightforward thought.

unpacking works when inside function call:

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

using elsewhere cause error:

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

in python 2.7, print not function, statement. far interpreter concerned, this:

print(*[1,2,3]) 

is syntactically equivalent this:

print *[1,2,3] 

which invalid. in python 3.x, print function, unpacking work.

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

you can port functional print 2.7 importing future:

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

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -