Python lambda returns None instead of empty string

I have the following lambda function:

f = lambda x: x == None and '' or x 

It should return an empty string if it takes None as an argument, or an argument if it is not None.

For example:

 >>> f(4) 4 >>> f(None) >>> 

If I call f (None) instead of getting an empty string, I get None. I typed the type of the return function and got NoneType. I was expecting a string.

type ('') returns a string, so I would like to know why lambda does not return an empty string when I pass None as an argument.

I am new to lambdas, so I may have misunderstood some things about how they work.

+7
python lambda
source share
6 answers

use the if else construct

 f = lambda x:'' if x is None else x 
+17
source share

The problem in your case is that `` is considered the boolean value False. bool ('') == False. you can use

 f =lambda x:x if x is not None else '' 
+8
source share

The problem is that Python treats the empty string as False. When you pass None to your function, it evaluates:

 None == None and '' or None 

which (effectively) becomes:

 True and False or None 

then

 False or None 

and finally:

 None 

One solution:

 lambda x: x if x is not None else '' 

If you know that x will be either a string or None, then you can use the fact that None is also a False value in Python:

 lambda x: x or '' 
+4
source share

This is not lambda, this is the problem here. This is the pythonic if / else expressiong that you use there.

(condition) and (expression1) or (expression2) most of the time mean (condition) ? (expression1) : (expression2) (condition) ? (expression1) : (expression2) , which you expect, unless expression1 is False.

This is because all this is evaluated in order. If condition fails, expression1 is expression1 . If it is True , it returns due to the evaluation of the short circuit, hence the expected behavior. If not, expression2 returned. '' is False.

+2
source share

Try a short circuit rating :

  >>> g = lambda x: x or '' >>> g(3) 3 >>> g(None) '' >>> # beware that ... >>> g(0) '' 
+2
source share

Python gives and a higher priority than or , so the parentheses get here:

 lambda x: (x == None and '') or x 

When transmitting None it becomes (True and '') or None . Pythons Boolean operators work by returning one or more arguments (where this little trick comes from), so it boils down to '' or None and finally None .

This little trick comes from the previous version to Python 2.5, which did not have a conditional statement . The caveat you come across is that it does not behave as expected when the True branch is False . If you are not affiliated with Python ≤ 2.4, just use the conditional operator.

+2
source share

All Articles