17

Possible Duplicate:
Why does “[] == False” evaluate to False when “if not []” succeeds?

I am new to python as per ternary operator of python

>>> 'true' if True else 'false'  true
   true

i am expecting for below code output as [] because [] not equal to None

>>> a=[]
>>> a==None
False
>>> a if a else None
None

pleas correct if i am wrong

Thanks hema

Community
  • 1
  • 1
user1559873
  • 6,650
  • 8
  • 25
  • 28

2 Answers2

20

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!
jdotjdot
  • 16,134
  • 13
  • 66
  • 118
  • 18
    The easiest way to put it is `[] != False` but `bool([]) == False`. – Gareth Latty Dec 10 '12 at 17:37
  • 1
    @Lattyware True, it's the most concise way, but I'd think a Python newbie might have trouble following though. – jdotjdot Dec 10 '12 at 17:40
  • 1
    Oh, indeed, I'm not suggesting you remove your excellent explanation, just putting it another way. – Gareth Latty Dec 10 '12 at 17:41
  • 1
    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 Nov 08 '16 at 03:54
  • 1
    @VISQL you still don't need `bool([])`, you can just return `[]`, since `[]` evaluates false-y. – jdotjdot Nov 08 '16 at 14:55
2

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

Community
  • 1
  • 1
ank
  • 106
  • 5