Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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!

like image 720
Saurabh Jain Avatar asked Mar 12 '14 17:03

Saurabh Jain


2 Answers

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.") 
like image 74
ApproachingDarknessFish Avatar answered Oct 06 '22 09:10

ApproachingDarknessFish


left = None  left is None #evaluates to True 
like image 31
limasxgoesto0 Avatar answered Oct 06 '22 09:10

limasxgoesto0