Python lambda returning None instead of empty string

Posted by yoshi on Stack Overflow See other posts from Stack Overflow or by yoshi
Published on 2010-04-03T20:27:15Z Indexed on 2010/04/03 20:33 UTC
Read the original article Hit count: 335

Filed under:
|

I have the following lambda function:

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

It should return an empty string if it receives None as the argument, or the argument if it's not None.

For example:

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

If I call f(None) instead of getting an empty string I get None. I printed the type of what the function returned and I got NoneType. I was expecting string.

type('') returns string, so I'd like to know why the lambda doesn't return an empty string when I pass None as an argument.

I'm fairly new to lambdas so I might have misunderstood some things about how they work.

© Stack Overflow or respective owner

Related posts about python

Related posts about lambda