How to assign a NULL value to a pointer in python?

I am C programmer. I am new to python. In C , when we define the structure of a binary tree node we assign NULL to it's right and left child as :

struct node 
{
    int val;  
    struct node *right ;  
    struct node *left ;  
};   

And when initializing a node , we write as :

val = some_value  
right = NULL;  
left = NULL;  

Now my question is: how can we assign a NULL value to right and left pointers of the node in Python?

And how can we test against the Python version of NULL ? In C it would be:

if( ptr->right == NULL )

Thank you!


All objects in python are implemented via references so the distinction between objects and pointers to objects does not exist in source code.

The python equivalent of NULL is called None (good info here). As all objects in python are implemented via references, you can re-write your struct to look like this:

class Node:
    def __init__(self): #object initializer to set attributes (fields)
        self.val = 0
        self.right = None
        self.left = None

And then it works pretty much like you would expect:

node = Node()
node.val = some_val #always use . as everything is a reference and -> is not used
node.left = Node()

Note that unlike in NULL in C, None is not a "pointer to nowhere": it is actually the only instance of class NoneType. Therefore, as None is a regular object, you can test for it just like any other object with node.left == None. However, since None is a singleton instance, it is considered more idiomatic to use is and compare for reference equality:

if node.left is None:
   print("The left node is None/Null.")

left = None

left is None #evaluates to True

Normally you can use None, but you can also use objc.NULL, e.g.

import objc
val = objc.NULL

Especially useful when working with C code in Python.

Also see: Python objc.NULL Examples