NoneIntermediate Examples

Represents the absence of a value; Python's null equivalent

None as a default argument sentinel

Using None to detect whether an argument was passed.

python
def append_to(item, target=None):
    if target is None:
        target = []  # fresh list each call
    target.append(item)
    return target

a = append_to(1)
b = append_to(2)
print(a)
print(b)
print(a is b)
Expected Output
[1]
[2]
False

Never use a mutable default argument like def f(x=[]). Use None as a sentinel and create the mutable object inside the function.

Optional chaining with None

Safely navigating nested structures that may contain None.

python
data = {
    "user": {
        "address": {
            "city": "New York"
        }
    }
}

def safe_get(d, *keys):
    for key in keys:
        if d is None:
            return None
        d = d.get(key) if isinstance(d, dict) else None
    return d

print(safe_get(data, "user", "address", "city"))
print(safe_get(data, "user", "phone", "number"))
Expected Output
New York
None

Since Python has no optional chaining operator (?.), you need helper functions or try/except to safely navigate nested data.

Want to try these examples interactively?

Open Intermediate Playground