Suppose I have a function foo(x,k) and suppose x is a list. I want k to default to the length of the list. Do I just write:
def foo(x, k=1):
k = len(x)
..
end
I just want to run foo with one argument, namely, x.
Suppose I have a function foo(x,k) and suppose x is a list. I want k to default to the length of the list. Do I just write:
def foo(x, k=1):
k = len(x)
..
end
I just want to run foo with one argument, namely, x.
You should do:
def foo(x, k=None):
if k is None:
k = len(x)
...
Note that this could be made more compact as:
def foo(x, k=None):
k = k or len(x)
Just do:
def foo(x):
k = len(x)
You don't have to pass in k to this function. You can just use a local variable k.
In case you have to use k then you can just do:
def foo(x,k):
k = len(x)
Although this doesn't serve any purpose.
If your intent is to have an optional k in no particular order with k=len(l)
the default, you can use an optional keyword argument like so:
def f(l,**kwargs):
k=kwargs.get('k',len(l))
# if k is in kwargs, it overrides the default of len(l)..
print 'l={}, len(l)={}, k={}'.format(l,len(l),k)
f([1,2,3])
f([1,2,3],k=1)
Prints:
l=[1, 2, 3], len(l)=3, k=3
l=[1, 2, 3], len(l)=3, k=1
As pointed out in the comments, this is a trade-off with other considerations of speed and parameter position in David Robinson's approach.