"If not" condition statement in python

84,347

if is the statement. not start is the expression, with not being a boolean operator.

not returns True if the operand (start here) is considered false. Python considers all objects to be true, unless they are numeric zero, or an empty container, or the None object or the boolean False value. not returns False if start is a true value. See the Truth Value Testing section in the documentation.

So if start is None, then indeed not start will be true. start can also be 0, or an empty list, string, tuple dictionary, or set. Many custom types can also specify they are equal to numeric 0 or should be considered empty:

>>> not None
True
>>> not ''
True
>>> not {}
True
>>> not []
True
>>> not 0
True

Note: because None is a singleton (there is only ever one copy of that object in a Python process), you should always test for it using is or is not. If you strictly want to test tat start is None, then use:

if start is None:
Share:
84,347
kaka
Author by

kaka

Updated on July 24, 2022

Comments

  • kaka
    kaka almost 2 years
    if not start: 
       new.next = None 
       return new
    

    what does "if not" mean? when will this code execute?

    is it the same thing as saying if start == None: then do something?