syntax question

Chris Angelico rosuav at gmail.com
Sat Jun 2 07:22:40 EDT 2018


On Sat, Jun 2, 2018 at 9:08 PM, Sharan Basappa <sharan.basappa at gmail.com> wrote:
> Can anyone please tell me what the following line in a python program does:
>
> line = lambda x: x + 3
>
> I have pasted the entire code below for reference:
>
> from scipy.optimize import fsolve
> import numpy as np
> line = lambda x: x + 3
> solution = fsolve(line, -2)
> print solution

That creates a function. It's basically equivalent to:

def line(x):
    return x + 3

Normally you won't take a lambda function and immediately assign it to
a name. The point of a lambda function is that, unlike a def function,
it can be used directly in a function call - so you might do something
like this:

solution = fsolve(lambda x: x + 3, -2)

which will have the same effect as the code you showed. If you want it
to have a name, like this, just use 'def'.

ChrisA



More information about the Python-list mailing list