Python: None keyword in Python
None keyword 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 What’s the difference between is and == in Python?
The == operator is for value equality. It’s used to know if two objects have the same value. The is operator is for reference equality. It’s used to know if two references refer (or point) to the same object, i.e if they’re identical. Two objects are identical if they have the same memory address. Two objects having equal values are not necessarily identical.
- In a few words:
- Put simply:
==determines if the values of two objects are equal, whileisdetermines if they are the exact same object. - or even simpler: the
isstatement is syntactic sugar forid(a) == id(b). - The
id()function is a built-in function in Python. It accepts a single parameter and is used to return the identity of an object.
- Put simply:
3 None Keyword
Noneis 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:
4 Comparison with None
- There are several ways to compare if a variable is
None:- The recommended and idiomatic way to check if a variable is
Noneis using theiskeyword. - Using
==works in most cases but can lead to incorrect results in some specific advanced cases.
- The recommended and idiomatic way to check if a variable is
Example:
The is keyword works because Python stores a single instance of None in memory. Every variable equal to None points to the same memory location.
To check if a variable is not None, use a combination of is not:
None evaluates to False in a condition similar to False, empty strings '', or 0.
Example:
5 Returning None in Functions
None is commonly used in the context offunction 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. - Good choice when the function is only meant to perform an action (like printing or updating), and the caller (
return) does not need to use the return value.
5.2 Only Return (without expression)
- Writing
returnwithout a value also returnsNone. - Used to explicitly indicate the function should return early without any result.
5.3 Explicitly return None
- Explicitly returns
None. - Makes it clear the function intentionally returns
None. - Normally understood as not having any value.