PythonPython Variables and Data TypesPython data types
What is the `None` type in Python?
Question 36 of 88 · Updated
On this page
- 1. None versus NoneType
- 2. None is different from other falsy values
- 3. Why functions sometimes return None
- 4. Practical example: return an optional search result
- 5. None as a default argument
- 6. Missing dictionary key versus a key with value None
- 7. When you need a sentinel distinct from None
- 8. In-place methods that return None
- 9. Python None and JSON null
- 10. Common None-related errors
- 11. Best practices
- Frequently asked questions
- Is None the same as null?
- What is the type of None?
- Is None a Boolean?
- Can a Python variable be initialized to None?
- Does None mean an error occurred?
- Can None be a dictionary key?
- Interview-ready answer
- Official references
None is Python's special singleton object representing the absence of a value or result. Its type is NoneType, and None is the only instance of that type. It is commonly used for optional parameters, missing information, unsuccessful lookups and functions that do not return a meaningful result.
None is not zero, False, an empty string or an undefined variable. It is a real Python object with a particular meaning that your program must define and handle.
1. None versus NoneType#
PYTHONfrom types import NoneType x = None y = None print(type(x).__name__, type(x) is NoneType, x is y) print(NoneType() is None)
Output:
NoneType True True
TrueNone is the object; NoneType is its type. The standard-library types.NoneType name is available in Python 3.10 and later. The portable expression type(None) also identifies the type.
A singleton is a type with one instance in this context. Assigning None to multiple names does not create multiple distinct None objects. None is immutable and hashable. You cannot assign to the keyword None itself.
The Python language guarantees the singleton semantics; there is no need to rely on a particular memory address or implementation-specific reference count.
2. None is different from other falsy values#
Several Python values evaluate to False in a Boolean context, but that does not make them equivalent to None.
PYTHONfor value in (None, False, 0, '', []): print(repr(value), bool(value), value is None)
Output:
None False True
False False False
0 False False
'' False False
[] False False| Value | Type | Typical interpretation |
|---|---|---|
| None | NoneType | Absent or unspecified value |
| False | bool | Negative logical state |
| 0 | int | An actual numerical value |
| '' | str | An actual string of length zero |
| [] | list | An actual collection with no elements |
Prefer an identity check, is None, when the condition specifically concerns absence. Use a truth-value test when any falsy value has the intended meaning.
An undefined name is different again: evaluating a name that cannot be resolved raises NameError. Assigning x = None explicitly initializes a name to a valid object.
3. Why functions sometimes return None#
Python functions return None if execution reaches the end of the body without a return statement specifying a result. A bare return statement also returns None.
PYTHONdef record_event(events, event): events.append(event) def stop(): return events = [] print(record_event(events, 'started') is None, events) print(stop() is None)
Output:
True ['started']
TrueThe first function performs a side effect by modifying the supplied list. Its return value is None because it does not explicitly return another value.
A function returning None has not necessarily failed. The function's documented contract determines what the result means. None can indicate successful completion of a side effect, absence of data or a deliberate optional result. Unexpected None values may also reveal a missing return statement on one execution path.
This rule applies to ordinary synchronous functions. Generator and coroutine execution have additional protocol semantics that should be considered separately.
4. Practical example: return an optional search result#
A search function can return an index when it finds an item and None when it does not.
PYTHONdef find_index(items: list[str], target: str) -> int | None: for index, item in enumerate(items): if item == target: return index return None for target in ('pen', 'bag'): index = find_index(['pen', 'book'], target) print('Missing' if index is None else f'Found at {index}')
Output:
Found at 0
MissingThe first matching item is at index zero. If the caller had written if index instead of testing index is None, it could incorrectly interpret that successful result as absent.
For n items, this search makes at most n equality comparisons, with O(1) auxiliary storage excluding the input and any cost of comparing the strings. It stops on the first match. Python's built-in list.index follows a different contract: it raises ValueError when an item is absent. Either design is valid when callers know which contract applies.
Use a return annotation to communicate that None is a possible outcome. The notation int | None requires Python 3.10 or later. typing.Optional[int] is an alternative notation expressing the same type union. An annotation does not itself perform runtime validation or prevent the function from returning an unexpected value.
5. None as a default argument#
None can represent an omitted argument when the application does not need to distinguish omission from an explicit None.
PYTHONdef effective_limit(limit: int | None) -> int: return 10 if limit is None else limit print(effective_limit(None), effective_limit(0))
Output:
10 0The function preserves a legitimate zero instead of replacing it with the default. This pattern is often better than limit or 10, which would replace any falsy operand.
The example assumes callers supply an integer or None. A real service should validate its own input constraints, including any permitted range.
Another familiar use is replacing a mutable default argument with None, then constructing a fresh list or dictionary inside the function. This avoids sharing a single mutable default object between calls. The earlier mutability lesson demonstrates that behavior in detail.
An optional type and an optional argument are related but different concepts. A parameter annotated int | None can accept None without having a default; a parameter with a default value can be omitted when called. Neither implies the other.
6. Missing dictionary key versus a key with value None#
A dictionary can store None as a legitimate value. The get method returns None by default if the key is missing, so get alone cannot distinguish these two cases.
PYTHONrecord = {'phone': None, 'count': 0} print(record.get('phone'), record.get('email')) print('phone' in record, 'email' in record)
Output:
None None
True FalseThe phone key exists and its value is None. The email key does not exist. Use membership testing or an explicit unique default object when the distinction is meaningful.
This arises in configuration, partial updates, caches and imported records. The absence of a key and a present key with an absent value may correspond to different application states.
7. When you need a sentinel distinct from None#
Suppose a profile update has three meanings:
- Omitted nickname: preserve the existing value.
- Explicit None: clear the nickname.
- A supplied string: replace the nickname.
Using None as the default would collapse the first two cases. Instead, create a unique object and compare by identity.
PYTHONMISSING = object() def update_nickname(record, nickname=MISSING): if nickname is not MISSING: record['nickname'] = nickname return record profile = {'nickname': 'Ash'} print(update_nickname(profile)) print(update_nickname(profile, None))
Output:
{'nickname': 'Ash'}
{'nickname': None}This uses a module-level sentinel whose identity is distinct from None and other ordinary values. The same sentinel object must be used at the comparison point.
The function intentionally modifies the input dictionary. Its example contract assumes a nickname is either an acceptable string or None; validation and authorization would be required at a real profile-update boundary. A local object sentinel is not itself a serializable protocol value. When processing a JSON request, inspect whether the field is present and translate the external representation into internal states deliberately.
8. In-place methods that return None#
Many methods that modify an object in place return None rather than returning the modified object. For example:
PYTHONitems = [3, 1, 2] result = items.sort() print(items, result) print(sorted([3, 1, 2]))
Output:
[1, 2, 3] None
[1, 2, 3]list.sort modifies the original list and returns None. sorted creates a new sorted list from an iterable.
A frequent mistake is assigning items = items.sort(). The original list is sorted, then the name items is rebound to None. The name no longer refers to the list. Other aliases can still refer to that list.
Check the specific method's documented contract; not all mutating operations return None. For instance, list.pop mutates a list and returns the removed item.
9. Python None and JSON null#
JSON has a null value, corresponding to Python None when using the standard-library json module.
PYTHONimport json encoded = json.dumps({'nickname': None}) print(encoded) print(json.loads(encoded)['nickname'] is None)
Output:
{"nickname": null}
TrueThe JSON literal null is not valid Python source for the None object, and Python's None spelling is not the JSON null literal.
In APIs, a missing field and an explicit null field can have different semantics. A schema or application contract should define whether null is allowed and how omissions are handled.
Similarly, databases may expose SQL NULL through Python None, depending on the database driver and conversion rules. SQL's three-valued logic and NULL comparison rules are not identical to Python's equality and Boolean semantics.
10. Common None-related errors#
| Expression or mistake | Result or explanation |
|---|---|
| Reading an undefined name | NameError |
| None + 1 | TypeError |
| len(None) | TypeError |
| None.upper() | AttributeError |
| Assigning the return value of list.sort to the list name | Name becomes bound to None |
| Treating a valid zero as missing | Incorrect default or search handling |
| Assuming an annotation initializes a name | A runtime binding may not exist |
The four exceptions in the first four rows were tested independently.
When diagnosing an unexpected None, find where it originated: a missing explicit return, a failed optional lookup, an in-place method, an omitted field or a caller supplying None. Then decide whether None should be handled, rejected or eliminated from the upstream contract.
Do not merely catch AttributeError around a large block of code to conceal an unexpected None. That may hide unrelated programming errors. Validate the relevant object and narrow the error-handling boundary.
11. Best practices#
- Use None when absence is a meaningful part of a function or object's contract.
- Use is None or is not None to test the singleton explicitly; equality can invoke user-defined comparison behavior.
- Distinguish None from legitimate falsy values such as zero and empty collections.
- Document optional results using an appropriate type annotation and test both present and absent cases.
- Use a distinct sentinel or membership check if omitted and explicitly empty values mean different things.
- Check method return contracts before assigning results or chaining operations.
- Avoid silently masking an unexpected None with arbitrary defaults.
Frequently asked questions#
Is None the same as null?#
None is Python's singleton for absence. JSON null maps to None through the standard JSON decoder, but each language or protocol defines its own semantics.
What is the type of None?#
Its type is NoneType, accessible through type(None) or types.NoneType in Python 3.10 and later.
Is None a Boolean?#
No. It is falsy when tested as a condition, but its type is NoneType, not bool.
Can a Python variable be initialized to None?#
Yes. An assignment such as result = None establishes a real name binding. It is not an uninitialized variable.
Does None mean an error occurred?#
Not necessarily. It can represent an absent result or successful completion of an operation without a meaningful return value. The documented contract determines its meaning.
Can None be a dictionary key?#
Yes. None is hashable. Whether it is an appropriate key depends on the data model.
Interview-ready answer#
None is Python's immutable singleton object of type NoneType, commonly used to represent the absence of a value or meaningful return result. An ordinary function with no explicit return value returns None. None is falsy but distinct from False, zero and empty collections, so use is None when checking specifically for absence. It is often used for optional arguments and return values, but when omission and explicit None have different meanings, use a separate sentinel or a membership check. Type annotations such as int | None communicate optional values without automatically enforcing them at runtime.
Official references#
- Python Language Reference — Data model: None
- Python Standard Library — Built-in Constants
- Python Standard Library — types.NoneType
- Python Language Reference — The return statement
- Python Standard Library — typing.Optional
- Python Standard Library — json
- PEP 8 — Programming recommendations
Verification note: Nine runnable examples were executed in independent namespaces on CPython 3.13.5 and matched their documented outputs. Four additional expected-exception tests passed. The Mermaid flowchart uses standard fenced syntax and was manually checked for logical branches and valid labels; the local Mermaid package and CLI were unavailable, so parser-level and live-site rendering remain unverified. Official reference links are supplied under the authorised offline research exception and were not checked live.
References
- 1.Python Language Reference — Data model: Nonedocs.python.org
- 2.Python Standard Library — Built-in Constantsdocs.python.org
- 3.Python Standard Library — types.NoneTypedocs.python.org
- 4.Python Language Reference — The return statementdocs.python.org
- 5.Python Standard Library — typing.Optionaldocs.python.org
- 6.Python Standard Library — jsondocs.python.org
- 7.PEP 8 — Programming recommendationspeps.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design