What is NoneType Object in Python
In Python, there is no null keyword, but there is None. None is the return value of the function that “doesn’t return anything“. None is often used to represent the absence of a value, as default parameters are not passed to the function. You can not assign a null value to the variable, and if you do, then it is illegal, and it 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
Keypoints of None in Python
- 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.
NoneType Object in Python
The None keyword is an object in Python, and it is a data type of the class NoneType. We can assign None to any variable, but we can not create other NoneType objects. NoneType is simply the type of the None singleton.
print(type(None))
Output
<class 'NoneType'>
To check the data type of variable in Python, use the type() method.
If the Python regular expression in the re.search does not match, it returns the NoneType object.
Checking if a variable is None
To check a variable is None or not, use the is operator in Python. With the is operator, use the syntax object is None to return True if the object has type NoneType and False otherwise.
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
You can see that is operator returns True because data is None, and hence if condition returns True and execute its body, which will print the “It is in fact a None“.
Comparing None with False type
You can compare the None with False value, but it returns False since False and None are not the same value.
data = None print(data == False)
Output
False
The None keyword is also used for matching or identifying if a certain function returns any value or not.
TypeError: ‘NoneType’ object is not iterable
For an object to be iterable in Python, it must include a value. A None value is not iterable because it does not hold any values or objects. None represents the null value in Python.
There is a difference between a None object and an empty iterable. The ‘NoneType’ object is not iterable error is not generated if you have any empty list or a string.
Technically, you can prevent the NoneType exception by checking if a value is equal to None using is operator or == operator before you iterate over that value.
To solve the NoneType error, make sure that any values you try to iterate over should be assigned an iterable object, like a string or a list.