Python: None in Python
Python None in Python
python
None
Python None in Python
1 Overview
๐ None in Python
In Python, None is a special constant that represents the absence of a value or a null value. It is often used to initialize variables or to indicate that a variable has not been assigned a value yet. None is an object of its own data type, NoneType.
2 None Keyword
None
is a special constant representing the absence of a value or a null value.- It is commonly used as a placeholder to indicate that a variable should not have any value.
Example:
3 Comparison with None
- The recommended and idiomatic way to check if a variable is
None
is using theis
keyword. - Using
==
works in most cases but can lead to incorrect results in some specific advanced cases.
Example:
- The
is
keyword works because Python stores a single instance ofNone
in memory. - Every variable equal to
None
points to the same memory location.
- To check if a variable is not
None
, use:
4 None Evaluates to False
None
evaluates asFalse
in boolean contexts, similar toFalse
, empty strings''
, or0
.
Example:
5 Returning None in Functions
None
is commonly used in function returns to indicate absence of value. There are different ways to return None
:
5.1 No return statement
- A function without a return statement implicitly returns
None
. - Useful when a function is meant to perform an action (like printing or updating), and the return value is not needed.
5.2 Return without expression
- Writing
return
without a value also returnsNone
. - Used to explicitly return early without any result.
5.3 Explicit return None
- Makes it clear the function intentionally returns
None
. - Typically used to indicate an absence of a matching result or value.
def find_contact_by_name(name, contacts):
for contact in contacts:
if contact["name"] == name:
return contact
return None
contacts = [
{"name": "Alice", "phone": "555-1234"},
{"name": "Bob", "phone": "555-5678"},
{"name": "Charlie", "phone": "555-8765"},
]
search_name = "David"
result = find_contact_by_name(search_name, contacts)
print(result) # None