12
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?

Mike Müller
  • 82,630
  • 20
  • 166
  • 161
kaka
  • 597
  • 3
  • 5
  • 16
  • 4
    `if` is the statement. `not start` is the expression, with `not` being an operator. – Martijn Pieters Dec 19 '15 at 23:23
  • @rnrneverdies although this is a great question, I don't think it speaks to the confusion OP is having (e.g. what does `if not` do?). Instead it talks about the distinction between `if `, `if ==`, and `if is ` – Adam Smith Dec 19 '15 at 23:27

2 Answers2

17

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:
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

It executes when start is False, 0, None, an empty list [], an empty dictionary {}, an empty set...

Pynchia
  • 10,996
  • 5
  • 34
  • 43