Python None
In this page:
variable = None
if variable is None:
# no value assigned
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 # represents the absence of a value
print(result)
print(type(result)) # shows <class 'NoneType'>
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") # log() has no return statement, so it implicitly returns None
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): # None avoids the mutable-default-argument pitfall
if items is None:
items = [] # a fresh list is created on every call
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) # None can be stored and searched for like any value
print(None == None) # comparing None to itself is True
- Testing for
Nonewith== Noneinstead ofis None, which is the recommended identity check. - Printing the result of a function that has no
returnand being surprised to seeNone. - Calling a method on a
Nonevalue, such asresult.upper()whenresultisNone, which raisesAttributeError.
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: