errolflynn
errolflynn

Reputation: 641

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

Upvotes: 3

Views: 91

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121594

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
... 

Upvotes: 6

Related Questions