[Tutor] lambda in python
Steven D'Aprano
steve at pearwood.info
Sat Nov 27 02:31:44 CET 2010
john tsolox wrote:
> since in Java i can pass an anonymous class to a function, and this anon class has member functions that can contain a
> body of implementation codes having the full expression of permissible syntax (if,for,while...), my question is, after
> seeing various examples of lambda in python being ALL one-liners. These one-liners inside a lambda seems not to have the
> full permissible use of the full power of python language (if,for,while). Is this correct?
>
> Is it correct to say, that within python lambda, you are not allowed to use 'if' ? pls enlighten...
Python lambda is syntactic sugar for an anonymous function, not a class.
Lambda is also limited to only a single expression. However, you can use
the ternary if:
lambda x: x+1 if x < 0 else x-3
is almost the same as:
def func(x):
if x < 0: return x+1
else: return x-3
--
Steven
More information about the Tutor
mailing list