How do I write a python lambda with multiple lines?

In python, how can you write a lambda function with multiple lines. I tried

d = lambda x: if x:
                 return 1
              else 
                 return 2

      

but i am getting errors ...

+3


source to share


3 answers


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.)

+12


source


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

      

+4


source


Here is the correct version of what you are trying to do:

d = lambda x: 1 if x else 2

      

But I'm not sure why you want to do this.

+2


source







All Articles