0

In C/C++, true is standardized as 1, and false as 0. Although not a good practice,

if variable:  
    #do something

kind of decision making seems ok in python and it seems makes decision based on whether variable is None or is zero - if it is a number. Followings are reasonable.

a = 123123
if a:
    print "if condition is true"  # this prints

a = "a string"
if a:
    print "if condition is true"  # this prints

a = None
    if a:
        print "if condition is true"  # this does not print

However, I wonder why it evaluates to false with an empty list, which is neither None, nor zero. What is the exact implementation of python if statement?

a = [] # a is not  None
if a:
   print "true" # this does not print
heral
  • 53
  • 1
  • 7

2 Answers2

0

Lists are empty, so they're False, that's how python reacts, to know whether something is False so doesn't go trough, do:

>>> bool([])
False
>>> 

So it is False.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

An if statement requires a bool. That means the the expression following the if is analyzed is a boolean context. Said differently it is converted to bool.

If a bool context, the following items evaluate to False (non exhaustive list):

  • None
  • numeric 0
  • empty list
  • empty string
  • empty dict

Non null numerics and non empty iterables eveluate to True

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252