alinsoar
alinsoar

Reputation: 15793

Conditionals within lambda

I try to initialize an array with a lambda-function called by map, and to my surprize IF-ELSE is not valid inside lambda.

a = map( (lambda x: if (len(aDict[x])==m): return aDict[x] else: return false),
         aDict.keys())

This is the error I get

File "objects.py", line 63
a = map( (lambda x: if (len(aDict[x])==m): return aDict[x] else: return false),
                     ^
SyntaxError: invalid syntax

What is the reason this does not work?


EDIT:

Now I discovered the interesting alternative expression

>>> False and 'one' or 'two'
'two'
>>> True and 'one' or 'two'
'one'

Very interesting... This is One-liner expression , this is why it wor

Upvotes: 1

Views: 960

Answers (1)

Silas Ray
Silas Ray

Reputation: 26160

You can't use that syntax inside a lambda, nor can you explicitly return. Try this instead:

lambda x, m: aDict[x] if (len(aDict[x])==m) else False

Lambda functions implicitly return the value resulting from evaluating the code in them. The code has to be expressible as a single compound expression (aka a one-liner) though.

Upvotes: 5

Related Questions