Question

I would expect an empty list to value test as False, but I'm a bit confused why a reference for a list containing an object reports as False also when value tested as in the following example:

>>> weapon = []
>>> weapon == True
False
>>> weapon.append("sword")
>>> weapon == True
False
>>> weapon
['sword']

If weapon = [] is False, why would weapon = ['sword'] also be False? According to docs http://docs.python.org/release/2.4.4/lib/truth.html, it should be True. What am I missing in my understanding of this?

Was it helpful?

Solution 3

You need to use bool() if you want to compare it directly

>>> weapon = []
>>> bool(weapon) == True
False
>>> weapon.append("sword")
>>> bool(weapon) == True
True

When you test a condition using if or while, the conversion to bool is done implicitly

>>> if weapon == True:  # weapon isn't equal to True
...     print "True"
... 
>>> if weapon:
...     print "True"
... 
True

OTHER TIPS

you should do a check like

In [1]: w = []

In [2]: if w:
   ...:     print True
   ...: else:
   ...:     print False
   ...:
False

When you do:

w = []
if w:
    print "Truthy"
else:
    print "Falsy"

the key thing to note is that whatever you are testing in the if clause is coerced to a boolean. To make it explicit:

w = []
if bool(w):
    print "Truthy"
else:
    print "Falsy"

To compare apples to apples then you don't want to compare ["sword"] to True. Instead you want to compare bool(["sword"]) to True:

bool(["sword"]) == True
# True

From that article, note that even things are considered to have a "true" truth value, they are not necessarily == True. For example:

["hi"] == True 
// False

if ["hi"]:
    print("hello")
// prints hello

The documentation says "Any object can be tested for truth value" not that [] == False or ['whatever'] == True. You should test objects as specified in the documentation "for use in an if or while condition or as operand of the Boolean operation".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top