[Tutor] Using lambda

Alan Gauld alan.gauld at btinternet.com
Mon Aug 24 10:11:33 CEST 2015

On 24/08/15 07:38, rakesh sharma wrote:
> I am beginner in pythonI see the use of lambda has been for really simple ones as in the numerous examples over the net.Why cant we use lambda in another one like g = lambda x: (lambda y: y + 1) + 1when I am able to do that in two lines
> h = lambda x: x + 1>>> h(12)13y = lambda x: h(x) + 1>>> y(1)3

Your email has arrived with no formatting so its hard to work
out your examples.

You can use lambda in multiple lines but it is limited
to a single expression.

 >>> ml = lambda n: (
...          5*n + (
...          n*n - (
...          25)))
 >>> ml(7)

And you can use lambda within a lambda:

 >>> adder = lambda x: lambda n: n+x
 >>> adder(3)
<function <lambda> at 0x7fe3dca0ccf8>
 >>> add3 = adder(3)
 >>> add3(5)

But for longer functions you are better using def to define them.
In Python lambda is not the underlying mechanism for creating
functions it is a convenience feature. Python is not Lisp.

Alan G
Author of the Learn to Program web site
Follow my photo-blog on Flickr at:

More information about the Tutor mailing list