I'm studying Python's ternary operator. I tried this code:
>>> a=[]
>>> a==None
False
>>> a if a else None
None
I don't understand the last result - I think it should be [] instead. Is the list equal to None or not?
I'm studying Python's ternary operator. I tried this code:
>>> a=[]
>>> a==None
False
>>> a if a else None
None
I don't understand the last result - I think it should be [] instead. Is the list equal to None or not?
The empty list, [], is not equal to None.
However, it can evaluate to False--that is to say, its "truthiness" value is False. (See the sources in the comments left on the OP.)
Because of this,
>>> [] == False
False
>>> if []:
... print "true!"
... else:
... print "false!"
false!
[] != False but bool([]) == False.return bool([]) is perfect for that.bool([]), you can just return [], since [] evaluates false-y.None is the sole instance of the NoneType and is usually used to signify absence of value. What happens in your example is that the empty list, taken in boolean context, evaluates to False, the condition fails, so the else branch gets executed. The interpreter does something along the lines of:
>>> a if a else None
[] if [] else None
[] if False else None
None
Here is another useful discussion regarding None: not None test in Python