简体   繁体   中英

How does “foo(*a)” work in Python?

Just switched from C++ to Python, and found that sometimes it is a little hard to understand ideas behind Python.

I guess, a variable is a reference to the real object. For example, a=(1,2,5) meaning a -> (1,2,5), so if b=a, then b and a are 2 references pointing to the same (1,2,5). It is a little like pointers in C/C++.

If I have:

def foo(a,b,c):
  print a,b,c

a=(1,3,5)
foo(*a)

What does * mean here?

Looks like it expands tuple a to a[0], a[1] and a[2]. But why print(*a) is not working while print(a[0],a[1],a[2]) works fine?

You seem to already understand that the asterisk is for argument unpacking . So the only confusion is about the print statement itself.

In python 3, print(*a) works fine:

>>> a=(1,3,5)
>>> print(*a)
1 3 5

In Python 2, however, it does not:

>>> a=(1,3,5)
>>> print(*a)
  File "<stdin>", line 1
    print(*a)
          ^
SyntaxError: invalid syntax

This is because print is not a function in Python 2, so Python 2 does not interpret the asterisk as argument unpacking instructions. In fact, print in Python 2 does not require parentheses. Wrapping a value with parentheses doesn't mean anything. (a) and a are the same. (Whereas (a,) is a tuple with one member.) So print (a) and print a are also the same.

You can, however, override the print statement with a print function from the future :

>>> from __future__ import print_function
>>> print(*a)
1 3 5

It doesn't work in Python 2 because there, print is not a function . It is a statement.

But, in Python 3, it will work as expected, because print is a function .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM