NoneType is a built-in data type that represents the absence of a value. It is the type of the None object, which is an object that indicates no value.
In Python, there is no null keyword, but there is None.
None is the only value of the NoneType data type.
None is a singleton, which means there is only one instance of NoneType in a runtime.
Visual representation
Example
print(type(None))
Output
<class 'NoneType'>
We can assign None to any variable, but we can not create other NoneType objects.
data = None
print(data)
Output
None
You can not assign a null value to the variable; if you do, it is illegal and will raise a SyntaxError.
data = null
print(data)
Output
Traceback (most recent call last):
File "/Users/krunal/Desktop/code/pyt/database/app.py", line 1, in <module>
data = null
NameError: name 'null' is not defined
Comparing None to anything will always return False except None itself.
- None is not a 0.
- None is not an empty string.
- None is not the same as False.
Checking if a variable is None
You can check if a variable is None by using the identity operator is
data = None
if data is None:
print("It is in fact a None")
else:
print("No, it is Not None")
Output
It is in fact a None
Comparing None with False type
It returns False since False and None are different.
data = None
print(data == False)
Output
False
Default Return Value of a Function
def function_without_return():
print("This function does not have a return statement.")
result = function_without_return()
print(result)
Output
This function does not have a return statement.
None
TypeError: ‘NoneType’ object is not iterable
TypeError: NoneType Object Is Not Iterable is an exception occurs when trying to iterate over a None value.
You can avoid this error by checking if a value is None or not before iterating over it. This can help ensure that only objects that have a value are iterated over, which avoids the error.
# Potentially problematic code
data = None # Assume this is the result of some operation that could return None
for item in data: # This will raise a TypeError
print(item)
Output
TypeError: 'NoneType' object is not iterable
Solution
# Safe approach
data = None
if data is not None: # Check if data is not None before iterating
for item in data:
print(item)
else:
print("Data is None, cannot iterate.")
Output
Data is None, cannot iterate.