Question

Python None: How to Represent a Null Value

pythonobjectnull

Question

How do I represent or refer to a null value in Python?

Short Answer

Python does not use a keyword named null. Instead, it uses the singleton object None to represent the absence of a value. You will learn how to assign, test, and use None safely in Python programs.

Concept

Python's equivalent of a null value is None.

result = None

None is a special built-in object that means no value is present, a value is unknown, or an operation has no meaningful result. Its type is NoneType.

print(type(None))  # <class 'NoneType'>

There is only one None object in a Python program. This is why Python code tests for it with identity operators:

if result is None:
    print("No result is available")

None matters because many functions, APIs, and optional variables need a clear way to distinguish “there is no value” from values such as 0, "", or False.

Mental Model

Think of a variable as a labeled box.

  • score = 0 means the box contains the number zero.
  • name = "" means the box contains an empty piece of text.
  • active = False means the box contains a false value.
  • email = None means the box currently has no email value at all.

None is not an empty string, zero, or False. It is a specific marker that says, “there is nothing here yet.”

Take Quiz

Syntax and Examples

Use None with a capital N and lowercase one.

user_address = None

Test whether a value is None with is or is not:

user_address = None

if user_address is None:
    print("Address has not been provided.")
else:
    print(user_address)

Use is not None when a value must be present before you use it:

age = 21

if age is not None:
    print(f"Age: {age}")

Many Python functions return None when they perform an action instead of calculating and returning a new value:

names = ["Ava", "Noah"]
returned_value = names.append("Mia")

print(names)           # ['Ava', 'Noah', 'Mia']
print(returned_value)  # None

append() changes the existing list, so it has no separate result to return.

Step by Step Execution

Consider this example:

def find_discount(code):
    discounts = {"SAVE10": 10, "SAVE20": 20}
    return discounts.get(code)

amount = find_discount("WELCOME")

if amount is None:
    print("Discount code was not found.")
else:
    print(f"Discount: {amount}%")

Step by step:

  1. find_discount("WELCOME") runs.
  2. The dictionary contains SAVE10 and SAVE20, but not WELCOME.
  3. dict.get() returns None when a key is missing and no fallback value was provided.
  4. amount is assigned None.
  5. amount is None evaluates to True.
  6. The program prints Discount code was not found.

This lets the program handle missing data without confusing it with a real discount such as 0.

Real World Use Cases

None is common whenever data may be optional or unavailable.

  • Database records: A user may not have supplied a phone number yet.
    phone_number = None
    
  • API data: A response may omit an optional field such as a profile image.
    avatar_url = response.get("avatar_url")
    
  • Search functions: A function may return None when it cannot find an item.
    product = find_product(product_id)
    
  • Optional function arguments: None can mean “use the default behavior.”
    def connect(timeout=None):
        if timeout is None:
            timeout = 30
    
  • In-place operations: Methods such as list.sort() and list.append() return None because they modify an existing object.
Take Quiz

Real Codebase Usage

In real projects, developers use None to model optional values and to make decisions before using data.

Guard clauses

Return early when a required value is missing:

def send_receipt(email):
    if email is None:
        return False

    print(f"Sending receipt to {email}")
    return True

Validation

Check that required input was provided:

def create_account(username, password):
    if username is None or password is None:
        raise ValueError("Username and password are required")

Defaults without overwriting valid false-like values

Use an explicit None check when 0, False, or an empty string are valid inputs:

def set_volume(volume=None):
    if volume is None:
        volume = 50
    return volume

print(set_volume(0))  # 0, not 50

Type hints for optional values

Python type hints can document that a function may return None:

from typing import Optional

def find_username(user_id: int) -> Optional[str]:
    if user_id == 1:
        return "Ava"
    return None

In Python 3.10 and later, this can also be written as str | None.

Common Mistakes

Writing null, NULL, or none

Python is case-sensitive and has no null keyword.

# Broken: NameError
value = null

Use None:

value = None

Comparing with == None

This often works, but is None is the recommended and clearest form. Equality can be customized by objects, while identity checks whether the value is the actual singleton None.

# Avoid
if value == None:
    pass

# Prefer
if value is None:
    pass

Treating None as the same as False, 0, or ""

All are false-like in a condition, but they mean different things.

value = 0

if not value:
    print("This runs, but value is not None")

When you specifically need to detect missing data, use is None.

Chaining a method that returns None

# Broken: append returns None
numbers = [3, 1, 2]
result = numbers.sort().append(4)

Call in-place methods separately:

numbers = [3, 1, 2]
numbers.sort()
numbers.append(4)

Using None as a mutable default

None is safe as a default marker, but use it to create a fresh mutable object inside the function.

def add_tag(tag, tags=None):
    if tags is None:
        tags = []
    tags.append(tag)
    return tags

Comparisons

ValueMeaningExample use
NoneNo value / value absentAn optional database field was not supplied
FalseA boolean negative resultA user is not signed in
0Numeric zeroA cart contains zero items
""Empty textA user submitted an empty comment
[]Empty listA search found no matching records

is versus ==

ExpressionWhat it checksUse with None?
value is NoneWhether value is the exact None objectYes, preferred
value is not NoneWhether a value is presentYes, preferred
value == NoneWhether value compares equal to NoneAvoid when testing for None

None versus a missing dictionary key

settings = {"theme": None}

print(settings.get("theme"))   # None: key exists, value is None
print(settings.get("language")) # None: key is missing

Both calls return None, so use "key" in settings when you must distinguish a missing key from a key explicitly set to None.

Take Quiz

Cheat Sheet

# Represent no value
value = None

# Preferred checks
if value is None:
    pass

if value is not None:
    pass

# Optional argument pattern
def greet(name=None):
    if name is None:
        name = "Guest"
    return f"Hello, {name}!"

# Safe mutable default pattern
def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items
  • Python uses None, not null.
  • None has type NoneType.
  • There is only one None object.
  • Prefer is None and is not None.
  • Do not use if not value when 0, False, "", or empty collections are valid values.
  • Many in-place methods return None.

FAQ

Is None the same as null in Python?

Conceptually, yes: None is Python's standard value for representing no value. Python does not have a null keyword.

Why should I use is None instead of == None?

None is a single shared object. is None directly checks for that object and is the standard Python style.

Is None false in an if statement?

Yes, None is false-like, so if None: does not run. However, it is distinct from False, 0, and empty collections.

Can a function return None?

Yes. A function with no return statement returns None automatically. Functions may also explicitly use return None.

How do I check whether a dictionary key is missing or has a value of None?

Use the in operator to check for the key:

if "theme" in settings:
    print(settings["theme"])

Can I use None as a default function argument?

Yes. It is especially useful as a marker for creating a new list or dictionary inside the function.

What happens if I print None?

Python displays the text None:

print(None)  # None
Take Quiz

Mini Project

Description

Build a small profile formatter that accepts optional user details. It demonstrates how None represents missing information and how explicit is None checks preserve valid values such as 0.

Goal

Create a function that displays a user profile while replacing missing values with helpful defaults.

Requirements

  • Create a function named format_profile that accepts name, age, and city.
  • Treat name and city as optional values.
  • Display "Anonymous" when name is None.
  • Display "Unknown" when city is None.
  • Preserve an age of 0 rather than treating it as missing.
  • Print the formatted result for two example profiles.
Take Quiz

Keep learning

Related questions

View more