Python
If not syntax
Programming
Conditional statements
Coding tips

Python 'If not' syntax

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Python's if not syntax negates a condition, executing the block when the expression evaluates to falsy. It is equivalent to if condition == False but more Pythonic and readable. The not operator works with any type — it returns True for falsy values (None, 0, "", [], {}, set(), False) and False for truthy values. Common uses include checking for empty collections, None values, and missing dictionary keys. Understanding truthiness is essential because if not x behaves differently than if x is None or if x == False.

Basic Syntax

python
1# if not negates the condition
2x = 0
3
4if not x:
5    print("x is falsy")  # Prints — 0 is falsy
6
7if not False:
8    print("This runs")   # Prints — not False is True
9
10if not None:
11    print("This runs")   # Prints — not None is True

not is a unary boolean operator. It converts the operand to a boolean and returns the opposite. not x is equivalent to True if bool(x) is False else False.

Checking Empty Collections

python
1my_list = []
2my_dict = {}
3my_string = ""
4
5# Pythonic — preferred
6if not my_list:
7    print("List is empty")
8
9if not my_dict:
10    print("Dict is empty")
11
12if not my_string:
13    print("String is empty")
14
15# Explicit but less Pythonic
16if len(my_list) == 0:
17    print("List is empty")

Empty collections are falsy in Python. if not my_list is the idiomatic way to check for an empty list, dict, string, tuple, or set. PEP 8 recommends this pattern over checking len().

Checking for None

python
1result = None
2
3# if not — matches None AND other falsy values
4if not result:
5    print("Falsy")  # Runs for None, 0, "", [], False
6
7# if is None — matches ONLY None
8if result is None:
9    print("None")  # Runs ONLY for None
10
11# Example where the distinction matters
12def get_count():
13    return 0  # Valid result, not an error
14
15count = get_count()
16
17if not count:
18    print("No count")  # WRONG — triggers for valid 0
19
20if count is None:
21    print("No count")  # CORRECT — only triggers for None

Use if not x when any falsy value should trigger the block. Use if x is None when you specifically need to check for None and 0, "", or [] are valid values.

Truthiness Table

python
1# All falsy values in Python
2not False      # True
3not None       # True
4not 0          # True
5not 0.0        # True
6not 0j         # True
7not ""         # True
8not []         # True
9not ()         # True
10not {}         # True
11not set()      # True
12not frozenset()  # True
13
14# All truthy — not returns False
15not True       # False
16not 1          # False
17not -1         # False
18not "hello"    # False
19not [1, 2]     # False
20not {"a": 1}   # False
21not " "        # False (space is not empty)

Combining with Other Operators

python
1x = 5
2y = ""
3z = [1, 2, 3]
4
5# not with and
6if not x and not y:
7    print("Both falsy")  # Does not run — x is truthy
8
9# not with or
10if not x or not y:
11    print("At least one falsy")  # Runs — y is falsy
12
13# not with in
14fruits = ["apple", "banana"]
15if "cherry" not in fruits:
16    print("No cherry")  # Runs
17
18# not with is
19value = 42
20if value is not None:
21    print("Has value")  # Runs

Note that not in and is not are separate operators from not. They are membership and identity tests with built-in negation, and they read more naturally than not x in y or not x is y.

Practical Patterns

python
1# Default value pattern
2def greet(name=None):
3    if not name:
4        name = "World"
5    print(f"Hello, {name}!")
6
7greet()          # Hello, World!
8greet("Alice")   # Hello, Alice!
9
10# Guard clause pattern
11def process_items(items):
12    if not items:
13        return []  # Early return for empty input
14
15    return [item.upper() for item in items]
16
17# Validation pattern
18def validate_form(data):
19    errors = []
20    if not data.get("email"):
21        errors.append("Email is required")
22    if not data.get("password"):
23        errors.append("Password is required")
24    return errors

Custom Truthiness with bool

python
1class Queue:
2    def __init__(self):
3        self.items = []
4
5    def __bool__(self):
6        return len(self.items) > 0
7
8    def enqueue(self, item):
9        self.items.append(item)
10
11q = Queue()
12
13if not q:
14    print("Queue is empty")  # Runs — __bool__ returns False
15
16q.enqueue("task")
17
18if not q:
19    print("Queue is empty")  # Does not run — __bool__ returns True

Classes can define __bool__ to control truthiness. If __bool__ is not defined, Python falls back to __len__ (truthy if non-zero), and if neither is defined, the object is always truthy.

Common Pitfalls

  • Using if not x when if x is None is intended: if not x matches None, 0, "", [], and False. If 0 or "" are valid values in your code, this creates a bug. Use if x is None to check specifically for None.
  • Double negation reduces readability: if not not x is equivalent to if x but harder to read. Similarly, if not x != y is confusing — use if x == y instead. Avoid unnecessary negation.
  • Confusing not in with not (in) precedence: not x in y and x not in y are equivalent, but not x in y reads as (not x) in y to some programmers. Always use x not in y for clarity — it is the recommended form.
  • Assuming if not x means x is False: if not x is true for any falsy value, not just False. not 0 is True, not "" is True, not [] is True. Only use if x is False when checking specifically for the boolean False.
  • Empty string vs None confusion: if not user_input treats both "" (user submitted empty form) and None (form field missing) the same way. If you need to distinguish between "empty" and "missing," check explicitly with is None and == "" separately.

Summary

  • if not x executes when x is falsy (None, 0, "", [], {}, False, set())
  • Use if not my_list to check for empty collections — it is the Pythonic idiom (PEP 8)
  • Use if x is None instead of if not x when 0, "", or [] are valid non-None values
  • not in and is not are separate operators that read more naturally than not x in y
  • Custom classes control truthiness via __bool__ and __len__ methods
  • Avoid double negation and prefer positive conditions when they are equally clear

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.