How do I write a python lambda with multiple lines?
Use def
instead.
def d(x):
if x:
return 1
else:
return 2
All python functions are first-order objects (they can be passed as arguments), lambda
it's just a convenient way to make them short. In general, you're better off using a standard function definition if it becomes more than one line of simple code.
Even then, if you assign a name to it, I will always use def
over lambda
. lambda
it is really a good idea when defining short key
functions to use with sorted()
, for example, since they can be embedded in a function call.
Note that in your case a 3-D operator would do the job ( lambda x: 1 if x else 2
), but I'm guessing this is a simplified case.
(As a code-style golf note, this can also be done in less code than lambda x: bool(x)+1
- of course, this is a very unreadable and bad idea.)
source to share
lambda
Python construct is limited to expression only , no assertions are allowed
Keeping the above restriction, you can write a multi-line expression using the backslash char, of course:
>>> fn = lambda x: 1 if x \
else 2
>>> fn(True)
>>> 1
>>> fn(False)
>>> 2
source to share