What is the Python equivalent of assigning NULL to a pointer in C?
As a C programmer new to Python, I’m trying to understand how to assign a NULL value to pointers in Python. In C, when defining the structure of a binary tree node, I assign NULL to its right and left children like this:
struct node
{
int val;
struct node *right;
struct node *left;
};
When initializing a node, we write:
val = some_value;
right = NULL;
left = NULL;
My question is: how can I assign a NULL value to the right
and left
pointers of the node in Python?
Also, how can I check for the Python equivalent of NULL? In C, it would be:
if(ptr->right == NULL)
Hi Shielagaa,
In Python, all objects are implemented via references, so there’s no distinction between objects and pointers to objects like in C. The Python equivalent of NULL is None. As all objects are references in Python, you can define your Node class like this:
class Node:
def __init__(self): # Object initializer to set attributes (fields)
self.val = 0
self.right = None
self.left = None
Now, you can use this class similarly to how you would in C:
node = Node()
node.val = some_val # Use . to access attributes, as everything is a reference (-> is not used)
node.left = Node()
To check if a node’s left or right pointer is None, you can use the following code:
if node.left is None:
print("The left node is None/Null.")
Note that None is a singleton instance, and it’s idiomatic to use is to compare it for reference equality, like node.left is None.
You could also use a more customized initialization method or data structure for handling None:
class Node:
def __init__(self, val=None, right=None, left=None):
self.val = val
self.right = right if right is not None else None
self.left = left if left is not None else None
This allows flexibility while still leveraging Python’s None to represent null references.
If you want to make it more explicit and work with typing, Python’s Optional type from the typing module can be used:
from typing import Optional
class Node:
def __init__(self, val: int = 0, right: Optional['Node'] = None, left: Optional['Node'] = None):
self.val = val
self.right = right
self.left = left
This approach helps in making it clear that the right and left attributes are either of type Node or None, making the code more self-documenting.