[Tutor] Using lambda
Cameron Simpson
cs at zip.com.au
Mon Aug 24 09:35:43 CEST 2015
On 24Aug2015 12:08, rakesh sharma <rakeshsharma14 at hotmail.com> 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) + 1
>
>when I am able to do that in two lines
>
> >>> h = lambda x: x + 1
> >>> h(12)
> 13
> >>> y = lambda x: h(x) + 1
> >>> y(1)
> 3
Hi,
First, please include more whitespace in your posts to make them easier to
read. If you are includining line breaks etc, I think something is eating them.
Regarding your question, you can do what you ask. You suggestion was:
g = lambda x: (lambda y: y + 1) + 1
The thing you've missed is that a lambda is a function; you need to call it.
Your example only defines a lambda but doesn't call it. Try this:
g = lambda x: (lambda y: y + 1)(x) + 1
which passes x through to the inner lambda:
>>> g(12)
14
So yes, you can do it. But as you can see it doesn't make for very readable
code. Lambdas are ok for small expressions. When things get more complex it is
worth breaking them up.
Cheers,
Cameron Simpson <cs at zip.com.au>
More information about the Tutor
mailing list