219

I'm a bit confused about how/why so many python developers use if not in their conditional statements.

for example, lets say we had a function,

def foo(bar = None):
    if not bar:
        bar = 2

But why go about this way? I mean, wouldn't doing if bar != None or if bar is not Nonebe more explicit? What does if not try to say?

2

1 Answer 1

278

Yes, if bar is not None is more explicit, and thus better, assuming it is indeed what you want. That's not always the case, there are subtle differences: if not bar: will execute if bar is any kind of zero or empty container, or False. Many people do use not bar where they really do mean bar is not None.

6
  • 1
    So if bar is [], then it will execute?
    – user1971598
    May 24, 2013 at 16:31
  • 3
    @EdgarAroutiounian Yes. Same or empty sets, tuples, dictionaries, strings, etc.
    – user395760
    May 24, 2013 at 16:32
  • 10
    Wow that's really confusing Aug 7, 2018 at 16:41
  • 24
    This is the best possible answer, bar none.
    – easeout
    Mar 7, 2020 at 22:50
  • Better Answer: stackoverflow.com/a/34376465/10730632 Feb 6, 2021 at 16:57