The result an expression (whether True or False), is determined by how it is expressed as a boolean expression. Python differs from strongly typed languages like Java in that any expression (even a variable reference) can be evaluated to a boolean. Refer to Truth Value Testing.
By default, an object is considered True unless its class defines either a bool() method that returns False or a len() method that returns zero, when called with the object.
Here are 3 statements to consider:
1. li = [""]
2. li == True
3. if li: print("li is true")
- Line 1, assign a non-empty list to variable li
- Line 2, list instance is not a boolean value so expression is evaluated as False, likewise
li == False
also evaluates to False.
- Line 3,
if li: ...
evaluates same as if bool(li): print... which evaluates to True and prints "li is true".
If evaluate the expression bool(li)
, the value is True since the list variable is non-empty and len() function returns 1. An empty List len() returns 0 so will return False.