Python None
In this page:
What Is None
None is Python's way of representing the absence of a value — it's a singleton object of its own type, NoneType, distinct from 0, an empty string, or False even though all of those are falsy. Variables are commonly initialized to None before being assigned something meaningful later.
Example: What Is None
result = None
print(result)
print(type(result))
Checking for None
Use 'is None' rather than '== None' to check for None — is compares object identity, and since None is a true singleton, identity comparison is both the idiomatic style (per PEP 8) and technically more correct, because a custom class could theoretically override == to behave unexpectedly.
Example: Checking for None
value = None
print(value is None)
None as a Default Return Value
A function with no explicit return statement, or a bare return with nothing after it, implicitly returns None — this is why forgetting a return statement in a function that's supposed to produce a value is a common source of silent bugs.
Example: None as a Default Return Value
def log(message):
print(message)
result = log("hi")
print(result)
None as a Default Argument
Using None as a default parameter value is the standard workaround for the classic mutable-default-argument pitfall — instead of writing 'def f(items=[])', which reuses the same list across calls, write 'def f(items=None)' and create a fresh list inside the function body when items is None.
Example: None as a Default Argument
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
print(add_item("apple"))
print(add_item("banana"))
None in Comparisons and Collections
None can be stored in lists, dictionaries, or any other collection just like any other value, and comparing None to itself with '==' works fine and returns True — it's only comparisons against other falsy values like 0 or '' where None correctly evaluates as not equal.
Example: None in Comparisons and Collections
values = [1, None, 3]
print(None in values)
print(None == None)
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: