Null in Python: What is None in Python

0
2325
Null Object In Python Example | Python Null Value Tutorial

Many programming languages use Null to represent a pointer that doesn’t point to anything. It’s a placeholder when a variable is empty or to mark default parameters that you haven’t supplied yet. The Null is often defined as 0 in those languages, but the Null in Python is different.

Null in Python

There’s no null in Python; instead, there’s None. Python null is called None, a particular object representing the absence of a value. Python Null object is the singleton None. The equivalent of the null keyword is None. Many would argue that the word “null” is somewhat esoteric.

Null is not precisely the friendliest word to programming novices. Also, “None” refers precisely to the intended functionality – it is nothing and has no behavior. In Python, None is the object and first-class citizen!

History of Null

In most object-oriented languages, the naming of objects tends to use camel-case syntax. E.g. ThisIsMyObject. As you’ll see soon, Python’s None type is an object and behaves like one.

As stated already, the most accurate way to test that something has been given None as the value is to use the is identity operator, which tests that two variables refer to the same object.

For example, in other programming languages, this is how you may create a null variable in PHP and Java. Let’s see how other Java and PHP define a Null variable.

Null in Java

myVariable = null;

Null in PHP

$myVariable = NULL;

If you need to evaluate a variable in the if condition, you may check this as follows in Java:

if(myVariable == null) {
  System.out.println(”Some output”);
}

How to use the ‘None‘ in Python. I will use it in the if statement and compound data types.

None in Python

None in Python is used to describe a null or no value. None does mean a value 0, False, or an empty string. None is data of its own (NoneType), and only None can be None. If you define a function with a return statement or no value, then it returns None.

def python_none():
    pass


print(python_none())

Output

None

When you call the python_none() function, it returns None because there is no return statement. Instead, there is only a pass statement.

None has no output value, but printing shows None to the Python console, explicitly forcing us to print the output.

None indicates missing or default parameters. For example, None appears twice in the docs for list.sort.

print(help(list.sort))

Output

sort(self, /, *, key=None, reverse=False)
    Sort the list in ascending order and return None.

    The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
    order of two equal elements is maintained).

    If a key function is given, apply it once to each list item and sort them,
    ascending or descending, according to their function values.

    The reverse flag can be set to sort in descending order.

In the output, you can see that the parameter key has a None value. That means the key parameter is required, but we have not provided it; that is why the default parameter is None.

Proof that None is Object

None is the singleton, and the NoneType class only gives you the same single instance of None. There’s only one None in our Python program.

NoneObj = type(None)()
print(NoneObj)

# Check if NoneObj is instance of NoneType class
print(NoneObj is None)

It gives the following output.

None
True

 Even though you try to create the new instance, you still get the existing None.

Interesting Facts about None

  1. None is not the same as False.
  2. None is not an empty string.
  3. None is not 0.
  4. Comparing None to anything will always return False except None itself.

Declaring None in Python

We can assign None object to any variable at the time of declaration. Python variables come to life by assignment operator, which helps us assign the particular value to the variable. Some programming languages don’t have to have an initial value assigned to them. For example, the initial value for some variables might be Null

Let’s assign the None value to a variable in Python and print the variable in the console.

data = None
print(None)

Output

None

 If we don’t define a variable and direct print its value, we will get NameError.

print(data)

Output

Traceback (most recent call last):
  File "app.py", line 2, in <module>
    print(data)
NameError: name 'data' is not defined

All variables in Python come into life by the assignment operator. A variable can only start life as Null if you assign None. If you don’t define a variable and directly try to print in the console, you will get NameError.

Return null in Python

To return a null in Python, use the None keyword. There is no such term as “return null” in Python. Every function returns some value. If no explicit return statement is used, Python treats it as returning None.

# app.py

def FuncNull(data):
    print(data)
    return None


print(FuncNull("Function Called"))

Output

Function Called
None

Python is not null

To check if a variable is null in Python, use the is not operator. Python is and is not operators are comparison operators that compare the identity of two objects. Python “is operator” is an identity test. It checks whether the right-hand side and the left-hand side are the very same object.

# app.py

var = "Stranger Things 4 Vecna"

if var is not None:
    print('Var is not null')

Output

Var is not null

You can see that var is not null or None that’s why if condition holds True and print the statement.

Using None as part of a comparison

There’s no null in Python. Instead, there’s None. As stated already, the most accurate way to test that something has been given None as a value is to use the is identity operator, which tests that two variables refer to the same object.

In Python, to represent an absence of the value, you can use a None value (types.NoneType.None) for objects and “” (or len() == 0) for strings.

Regarding the difference between “==” and “is,” testing for object identity using “==” should be sufficient.

However, since the operation “is” is defined as an object identity operation, it is probably more correct to use it rather than “==”. Not sure if there is even a speed difference.

An essential rule of thumb is to keep in mind when checking None values.

  1. Do use identity operators is and is not.
  2. Do not use the equality operators == and !=.

The difference between == and Python is Operator.

Difference between == and is operator in Python is that == operator compares the values of both the operands and checks for value equality. Whereas is operator checks whether both the operands refer to the same object. 

See the following code.

# app.py

eleven = None
print(eleven is None)

See the following output.

➜  pyt python3 app.py
True
➜  pyt

Now, see the following code.

def python_none():
    pass


data = python_none()
print(data == None)
print(data is None)

Output

True
True

This code returns None, and we check both ways that the data is indeed None.

But, The equality operators can be fooled when you’re comparing user-defined objects that override them.

class isAndDoubleEqual:
    def __eq__(self, other):
        return True


res = isAndDoubleEqual()
print(res == None)
print(res is None)

Output

True
False

The equality operator == returns the incorrect answer.

The identity “is operator” returns the correct answer because it can’t be fooled because you can’t override it.

Checking type of None

In other programming languages, Null is just a synonym for 0, but Null in Python is an object.

Check the type of None using the type() method.

print(type(None))

Output

<class 'NoneType'>

This shows that None is the object, and its data type is NoneType.

None by itself is built into the language as the Null in Python. However, you can check it out by printing the dir(__builtins__).

print(dir(__builtins__))

 It will print the following inbuilt items.

['ArithmeticError',..., None,....., zip

Using None as a Value in Python

We can pass None as a function parameter in Python and add it to the list. First, we will define a class, and we don’t define its body. Then, we create a function called list_function(), which takes two parameters.

  1. new_item: This item will be added to the list if we pass when calling the function.
  2. initial_list: As a default parameter, the list should be None, but if we pass any argument explicitly, it will return the initial list.
class DoAppendNone:
    pass


def list_function(new_item=DoAppendNone, initial_list=None):
    if initial_list is None:
        initial_list = []
    if new_item is not DoAppendNone:
        initial_list.append(new_item)
    return initial_list


data = [1, 2, 3, 4, 5]
print(list_function(initial_list=data))

Output

[1, 2, 3, 4, 5]

We have passed two parameters with its default value of the list_function(). 

  1. new_item = DoAppendNone
  2. initial_list = None

In the code, we have passed the initial_list as data because we have a data list that has five elements.

So, when calling the function, our initial_list = data.

That means, inside the function, we have checked if the initial_list is None or not, but it is not None as we have a list of items in data, so that condition will be False.

The second condition is that new_element should not be DoAppendNone, but it is. So that condition will be False also. So, no new element will be added to the list.

Finally, the provided data list will be returned as an output.

Now, what if None is a valid input object? For instance, what if list_function() could either insert an item to the list or not, and None was a valid element to append? In this case, you can define the class specifically for use as default while being distinct from None.

So, let’s write a program that inserts a None value as an element to the list.

class DoAppendNone:
    pass


def list_function(new_item=DoAppendNone, initial_list=None):
    if initial_list is None:
        initial_list = []
    if new_item is not DoAppendNone:
        initial_list.append(new_item)
    return initial_list


data = [1, 2, 3, 4, 5]
print(list_function(None, data))

Output

[1, 2, 3, 4, 5, None]

Here, the class DoAppendNone serves as a signal not to append, so you don’t want None for that. That frees us to insert None whenever you want.

Checking None using if…else condition.

We can write the following code to check if the value is None.

# app.py

value = None

if value is None:
    print('The value is null')
else:
    print('The value is not null')

In the above example, we have defined the variable called value and assigned the None value.

Then, we have used the if…else condition to check the None value, and if it does, return the print statement with “The value is null.”

We can use the following code to check if the name exists.

try:
    val
except NameError:
    pass  # val does not exist at all

There can be only one None in Python.

The None is the inbuilt constant as soon as you start Python, whether in a module, class, or function. The NonType, by contrast, is not; you’d need to get a reference to it first by querying None for its class.

>>> NoneType
NameError: name 'NoneType' is not defined
>>> type(None)
NoneType

None can be overwritten.

Before Python 2.4, it was possible to reassign None, but not anymore. Not even as the class attribute or in the confines of a function.

Checking if the value is None

Why do this

value is None

rather than

value==None

The first is equivalent to:

id(value)==id(None)

Whereas the expression value==None is applied like this,

value.__eq(None)__

if the value is None, then you’ll get what you expected.

>>> nothing = function_that_does_nothing()
>>> nothing.__eq__(None)
True

This is because none has a distinctive status in the Python language. It’s a preferred baseline value because many algorithms treat it as exceptional.

In such scenarios, it can be used as the flag to signal that the condition requires some special handling, such as setting the default value.

None in Tracebacks

When NoneType appears in your traceback, it means that something you didn’t expect to be None was None, and you tried to use it in a way that you can’t use None. Almost always, it’s because you’re trying to call a method on it.

data = [1, 2, 3, 4, 5]

data.append(6)
print(data)

data = None
data.append(11)
print(data)

Output

[1, 2, 3, 4, 5, 6]
Traceback (most recent call last):
  File "app.py", line 7, in <module>
    data.append(11)
AttributeError: 'NoneType' object has no attribute 'append'

When we define a list with some initial values, it can call the list.append() function to add an element to the list, but when we define a list to None, that means now that list is not a traditional Python list, that list is now None, and the None object does not have an append() method to work with that is why it throws an AttributeError.

When you see a traceback like the above in your code, look for the first attribute that raised the error. Here, it is an append() method. You’ll see the object you tried to call it on from there. Finally, figure out how that object became None and take the necessary steps to fix your code.

Conclusion

None in Python is an immutable keyword and powerful tool like True or False. None can be tested using in or not in operators. In tracebacks, None can be helpful to find the exact problem, and we can fix it by solving the Null issue.

There can be only one None in any Python program, and even if you create an instance of the NoneType class, there can only be one None.

That’s it for this tutorial.

Recommended Posts

Python Not Equal Operator

Python Absolute Value

Python sqrt()

Python stddev()

Python variance()

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.