3

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()?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
errolflynn
  • 641
  • 2
  • 11
  • 24

1 Answers1

6

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
... 
Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343