Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this lambda require *arg, what difference does it make?

Tags:

python

lambda

I came across a pretty clever little function that takes two functions, applies one on top of each other given an argument x:

def compose(f,g):
    return lambda *x: f(g(*x))

Now my issue is with *x, as I don't see it really doing anything here. Why couldn't it be simple x (without the asterisk)?

Here are my tests:

>>> def compose(f,g):
...   return lambda *x: f(g(*x))
... 
>>> this = lambda i: i+1
>>> that = lambda b: b+1
>>> compose(this,that)(2)
4

>>> def compose(f,g):
...   return lambda x: f(g(x))
... 
>>> compose(this,that)(2)
4

>>> def compose(f,g):
...   return lambda *x: f(g(*x))
... 
>>> compose(this,that)(2,2)
TypeError: <lambda>() takes exactly 1 argument (2 given)
like image 807
ApathyBear Avatar asked Jun 02 '15 19:06

ApathyBear


People also ask

What is a lambda argument?

A lambda function evaluates an expression for a given argument. You give the function a value (argument) and then provide the operation (expression). The keyword lambda must come first. A full colon (:) separates the argument and the expression. In the example code below, x is the argument and x+x is the expression.

Why do we need lambda functions?

Lambda functions are intended as a shorthand for defining functions that can come in handy to write concise code without wasting multiple lines defining a function. They are also known as anonymous functions, since they do not have a name unless assigned one.

How many arguments does lambda have?

A lambda function can take any number of arguments, but can only have one expression.

Can lambda take two arguments?

A lambda function is an anonymous function (i.e., defined without a name) that can take any number of arguments but, unlike normal functions, evaluates and returns only one expression.


1 Answers

If g (that in your tests) can also take a variable number of arguments, then lambda *x: f(g(*x)) can be useful.

Otherwise, not so much.

The aim is to allow the composed function to be invoked with any number of arguments, and for all these arguments to be passed to the inner function in the composition.

like image 129
Frédéric Hamidi Avatar answered Oct 19 '22 20:10

Frédéric Hamidi