简体   繁体   中英

List building in Python function definition

I would like to build a prototype as such:

def foo(a,t=([0]*len(a))):
  print t

For reasons that are unimportant at the moment. I am passing in variable length list arguments to . However, Python 2.7.10 on Linux always returns as follows:

>>> a = [1,2,3,4]
>>> foo(a)
[O, 0]

Without the function call, none of this behaves in an unexpected manner. What is happening that causes Python to always think that the passed list is length 2 during variable assignment in foo()?

You can't do what you want, because function defaults are executed at the time the function is created , and not when it is called.

Create the list in the function:

def foo(a, t=None):
    if t is None:
        t = [0] * len(a)
    print t

None is a helpful sentinel here; if t is left set to None you know no value was specified for it, so you create new list to replace it. This also neatly avoids storing a mutable as a default (see "Least Astonishment" and the Mutable Default Argument why that might not be a good idea).

Your example could only have worked if you already had defined a up front:

>>> def foo(a,t=([0]*len(a))):
...   print t
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> a = [1, 2]
>>> def foo(a,t=([0]*len(a))):
...   print t
... 

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