71

I am C programmer and new to Python. In C, when we define the structure of a binary tree node we assign NULL to its 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 )
2
  • 1
    None
    – Kevin
    Commented Mar 12, 2014 at 17:48
  • None, and is None. Commented Mar 12, 2014 at 17:48

4 Answers 4

95

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.")
0
9
left = None

left is None #evaluates to True
0
1

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

1
  • Link is dead. Is this the current documentation?
    – wjandrea
    Commented Dec 4, 2021 at 21:45
0

Also, I believe just testing the object itself without a comparison, validates against null/None. so:

if val is null: 

would be equal to:

if val:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.