19

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?

2

2 Answers 2

25

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!
Sign up to request clarification or add additional context in comments.

3 Comments

The easiest way to put it is [] != False but bool([]) == False.
Answer by @GarethLatty was what I was looking for. My function removes things from a list based on criteria and should return false overall if the list becomes empty. return bool([]) is perfect for that.
@VISQL you still don't need bool([]), you can just return [], since [] evaluates false-y.
4

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.