pythonic way of 'b = list(a); b.append(4)"

Peter Otten __peter__ at web.de
Thu Feb 16 12:44:49 EST 2006


szabi wrote:

> I have a list of three values and want to call a function with four
> parameters. I would like
> to write something like:
> 
> a = [1, 2, 3]
> f(*a, 4)
> 
> This is syntactically wrong, so is there a function which appends a
> value to a list and
> returns the new value, so that I could write something like this:
> 
> f(list(a).functional_append(4))
> 
> I can't modify 'a'.

Two more options: if you know the name of the function's fourth parameter
you can mix keyword and positional arguments

>>> def f(a, b, c, d):
...     return "f(a=%r, b=%r, c=%r, d=%r)" % (a, b, c, d)
...
>>> a = [1, 2, 3]
>>> f(d=42, *a)
'f(a=1, b=2, c=3, d=42)'

or you can use partial function application:

>>> def partial(f, *left):
...     def w(*right):
...             return f(*left+right)
...     return w
...
>>> partial(f, *a)(42)
'f(a=1, b=2, c=3, d=42)'

A generalized version of partial() will become part of the standard library
in Python 2.5.

Peter




More information about the Python-list mailing list