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

Steven D'Aprano steve at REMOVETHIScyber.com.au
Thu Feb 16 12:17:51 EST 2006


On Thu, 16 Feb 2006 08:04:43 -0800, szabi wrote:

> Hi!
> 
> 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))

Sure there is, just not as a list method. Python is a programming
language, you can write any function you like:

def functional_append(L, extra):
    """Return a new list consisting of extra appended to the items of L."""
    return L + [extra]

Now call it like this:

f(functional_append(a, 4))

But in fact you can now optimize the functional_append away by just doing
this:

f(*a+[4])

and it will work.


-- 
Steven.




More information about the Python-list mailing list