A funny thing about Python

Python has a way to convert arbitrary data types to Boolean (True/False). For example, an integer of value 0 will be converted to False, while any other integer will be converted to True. Empty sets are converted to False, sets that contain things are converted to True. So here are a few examples, as shown in a REPL (read, evaluate, print, loop) session:

>>> bool(0)
False
>>> bool(1)
True
>>> bool(2)
True
>>> bool([])
False
>>> bool([1])
True
>>> bool([1, 2])
True
>>> bool(True)
True
>>> bool(False)
False
>>> bool('True')
True

These should all make sense. Now for the funny part. Observe the REPL output below, which seems to give the wrong answers:


>>> bool('False')
True
>>> bool([False])
True
>>> bool([[]])
True

Of course, the first one is True because the interpreter is just checking to see if the string is empty or not, and it does not care what is in the string. Similarly, in the second and third examples the interpreter is just checking to see if there is an empty set. The False and the empty set are each taking up space and so the sets are not empty.

Python does give a way to check arrays, using the any and all built-in functions. Some examples:

>>> any([False, False])
False
>>> any([True, False])
True
>>> all([True, False])
False
>>> all([True, True])
True

One place to be careful, though, is with empty sets. Observe the following:

>>> any()
Traceback (most recent call last):
  File "<pyshell#75>", line 1, in 
    any()
TypeError: any() takes exactly one argument (0 given)
>>> any([])
False
>>> any([[]])
False
>>> any([[[]]])
True

I included the first to show that there is an error if you do not supply any set at all. The second is an empty set, which returns false since it does not contain anything. The third one is false since the innermost empty set contains one empty set, which converts to False (as we saw above), while the fourth one has a set containing a non-empty set, therefore it is equivalent to any([True]), which returns the expected True as seen above.

Tags: ,

Leave a Reply