Skip to main content

8.11) The True Nature Of Objects


In Python, all objects, whatever their type have inherent True or False properties.

The following values are considered false:

  • None
  • False
  • zero of any numeric type (integer, float or complex), for example, 0, 0.0, 0j
  • any empty sequence (e.g. string, list or tuple), for example, "", (), []
  • any empty mapping (i.e. dictionary), for example, {}
  • All other values are considered true, so most values are true in Python.

    So checking whether a Dictionary or sequence is empty or whether a value is None is really straightforward. For example, this will only print the first element of a list if the list is not empty otherwise, it prints 'empty list':

    >>> L=[] # initialise empty list
    >>> if L:
            print L[0]
        else:
            print 'empty list'
    empty list