1

I went through Truthiness in Python and understood that [] and similar empty objects are interpreted as False in Python.

But when I type in the following in REPL, it returns False:

>>> [] == False
False

How is this possible?

chaudharyp
  • 3,394
  • 3
  • 26
  • 42

2 Answers2

5

Because == doesn't check truthiness, it checks equality. Those two objects are of different types, so they are not equal.

If you want to explicitly see the truthiness of an object, convert it to bool:

>>> bool([])
False

Note you would never do this in real code, because the point of truthiness is that the conversion is implict. Rather, you would do:

if my_value:
    ...do something...
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • 2
    "Those two objects are of different types, so they are not equal" It is slightly more complex than that, though. E.g. if you declare your own class with `def __eq__(self, other): return True` then instances of that class will be equal to any(?) other object. – Hannes Ovrén Apr 08 '16 at 11:43
  • So, does `if` statement implicitly apply that conversion to `bool` by itself? If so, then why doesn't it apply the same conversion in `if [] == False`? Considering that `[]` is interpreted as `False` and `==` checks for equality of values, shouldn't it return `True`? – chaudharyp Apr 08 '16 at 11:43
  • `[]` is **absolutely not** interpreted as False, that is simply not true. It is False in a boolean context, that's all. – Daniel Roseman Apr 08 '16 at 11:45
  • 2
    @chaudharyp: The `if` statement sees if the *whole* expression is truthy, not each part of the expression. It converts `[] == False` to a boolean, not `[]` unless it is by itself. – zondo Apr 08 '16 at 11:45
  • Thanks @DanielRoseman and @zondo. That really helped. Going by the blog, I thought that `[]` is interpreted as `False`. – chaudharyp Apr 08 '16 at 11:52
-2

because == returns equality if the object equals to other...

in this case [] isnt None just an empty array e.g.:

if variable:
    print "true"
else:
    print "false"

if variable is empty string ('')or empty array ([]) this prints out false.

if variable == None:
    print "true"
else:
    print "false"

if variable is empty string ('') or empty array ([]) this prints out fasle, because its not None type (its type equals str or list).

==: returns True if 2 variables are equal

if : returns True if variable is not None and ist not empty instance (like empty array or string)

János Farkas
  • 453
  • 5
  • 14