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

Python

Python Problem Overview


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!

Python Solutions


Solution 1 - Python

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][4] to use is and compare for reference equality:

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

[4]: https://www.python.org/dev/peps/pep-0008/#programming-recommendations ""Comparisons to singletons like None should always be done with is or is not, never the equality operators.""

Solution 2 - Python

left = None

left is None #evaluates to True

Solution 3 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSaurabh JainView Question on Stackoverflow
Solution 1 - PythonApproachingDarknessFishView Answer on Stackoverflow
Solution 2 - Pythonlimasxgoesto0View Answer on Stackoverflow
Solution 3 - PythonkenorbView Answer on Stackoverflow