Open In App

Difference Between Nan and None in Python

Last Updated : 09 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Python is a dynamically typed language with multiple concepts which might get confusing as we get to the computational parts of the Python language. Understanding basic concepts becomes a part of getting to know about the thought process of working with such concepts. One of such ambiguities arrives when comparing two same-sounding but different concepts in Python named NaN value and None value. In this article, we will be discussing the difference between the NaN value and the None value in Python.

NaN in Python

NaN or Not a Number is considered to be a value that is either undefined or missing, for example, in any dataset any values that are missing could be defined as NaN value, the NaN value works as a placeholder here, which some other value could later replace. However, it still has a mathematical significance to it, it usually works as a placeholder when there is a computational problem and the value of every cell is important, therefore, considering the value to be NaN keeps the data consistent. The NaN value in Python could be represented as:

float("nan")

NaN values are commonly used for scientific computational purposes since a lot of real-world data might miss some of the data values. For example, if we want to find out the square root of a negative number let’s say -5 the output will be NaN value in NumPy.

Python3




import numpy as np
 
result = np.sqrt(-1.0)
print(f"The resulting value is '{result}' which has the datatype {type(result)}")


Output:

The resulting value is 'nan' which has the datatype <class 'numpy.float64'>

Identifying if NaN Values are Present in the Dataset

We can identify if a NaN value is present in the dataset by importing it into the Pandas library, here is a code example to exactly do that:

First we will be importing important libraries NumPy for mathematical computing and Pandas for data manipulation and then creating a Python dictionary and converting it into a Pandas DataFrame and then printing it.

Python3




import pandas as pd
import numpy as np
 
# Create a DataFrame with some NaN values
data = {
    'A': [1, 2, np.nan, 4],
    'B': [5, np.nan, np.nan, 8],
    'C': [10, 11, 12, 13]
}
df = pd.DataFrame(data)
 
# Printing the DataFrame
print("DataFrame:")
print(df)


Output:

DataFrame:
A B C
0 1.0 5.0 10
1 2.0 NaN 11
2 NaN NaN 12
3 4.0 8.0 13

None in Python

In Python, the None value describes the empty value or when the value of something is not present, it is commonly used when value is absent in a variable or parameter. None value also appears for a function which does not return any particular value.

For example, let’s create a function with no return value, we will use pass statement in the function:

Python3




def none_function():
    # This function does not return any value
    pass
 
result = none_function()
print("The result is of the datatype:", type(result))


Output:

The result is of the datatype: <class 'NoneType'>

Difference Between NAN and None in Python

Parameters

NaN

None

Type Check

NaN is a special type of floating point value belonging to class float.

None is a singleton object belonging to class NoneType.

Equality Check

We can check for the NaN value by using math.isnan() or if the value exist in a dataframe by using df.isna()

None value could be checked by the use of ‘is‘ keyword or “==” operator.

Use Case

NaN is usually used in place of undefined value or missing value.

None is used to represent absence of some value in Python

Comparison

NaN value is a result of some numerical operation which is not a valid number.

None is defined for a variable which is intentionally left empty or undefined

Operations

Mathematical operations performed on NaN often results in NaN.

Operations involving None results in error or None value itself

Representation

NaN is a floating-point value with standard representation.

None is a constant and is represented as ‘None

Collections

NaN is usually used in the context of numerical computation and not commonly used like None.

None can be an element of various data structures like lists, sets etc.

Below are some of the examples indicating the difference between Nan and None in Python:

Type Check

Through this code example we will be differentiating between NaN and None value with the help of their datatype, showcasing the difference in their datatype helps us understand that both the values have different significance.

Python3




# None example
none_value = None
print(f"Value: {none_value} is of type: {type(none_value)}")
 
# NaN example
import math
nan_value = math.nan
print(f"Value: {nan_value} is of type: {type(nan_value)}")


Output:

Value: None is of type: <class 'NoneType'>
Value: nan is of type: <class 'float'>

Equality Check

In this code example, we will be differentiating between NaN and None with the help of their particular equality checking modes, the equality of None could be checked with the help of ‘==’ operator and the equality of NaN could be checked with the help of ‘math.isnan()‘ method.

Python3




# None equality check
none_value_1 = None
none_value_2 = None
print(f"Equality Check for None: {none_value_1 == none_value_2}")
 
# NaN equality check
import math
nan_value_1 = math.nan
nan_value_2 = math.nan
print(f"Equality Check for NaN: {math.isnan(nan_value_1) and math.isnan(nan_value_2)}")


Output:

Equality Check for None: True
Equality Check for NaN: True

Arithematic Operation

In this code example we will be differentiating NaN and None values based on their behaviour while interacting with arithematic operators. The None variable interacting with integer will produce an error, meanwhile the NaN value does not gets affected with arithematic operation.

Python3




# None in arithmetic operations
none_value = None
try:
    result = none_value + 5
except TypeError as e:
    result = f"Error: {e}"
print(f"Result: {result}")
 
# NaN in arithmetic operations
import math
nan_result = math.nan + 5
print(f"Result: {nan_result}")


Output:

Result: Error: unsupported operand type(s) for +: 'NoneType' and 'int'
Result: nan


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads