Singly Linked List: A Python Implementation | Part 2 | __str__ Method
Erik Anderson
Posted on November 26, 2019
In the previous post, I started by making a Node class.
I also included an __init__
method, to make it easier to instantiate Nodes, and to ensure that each Node has the same attributes.
I then created and printed a node in the following way:
my_node = SLLNode(7, None)
print("Node with value {} and next node {}.".format(my_node.value, my_node.next_node))
That worked, but wouldn't it be nice if we could do something like print(node)
?
It turns out we can. We just need to define a __str__
method.
The definition looks like this:
# indented within class SLLNode
def __str__(self):
s = "Node with value {} and next node: {}.".format(self.value, self.next_node)
return s
The method __str__
works under the hood when we call print(my_node)
and creates a string representation of my_node
.
Let's test it to make sure it's working.
my_node = SLLNode(8, None)
print(my_node)
And the output is:
Node with value 8 and next node: None.
Now, you may have noticed that there is a potential bug lurking under the surface. How will __str__()
function when a Node points to another Node? Let's find out.
second_node = SLLNode(27, None)
first_node = SLLNode(14, second_node)
print(first_node)
Here's the output:
Node with value 14 and next node: Node with value 27 and next node: None..
Do you see what happened? It might help if I insert some extra formatting into the output, like so:
{Node with value 14 and next node: {Node with value 27 and next node: None.}.}
Turns out __str__
got called recursively; it used __str__
again and called it on the second_node
. This isn't necessarily the behaviour we want, because as the list gets longer the output could be really long and cumbersome to read.
I honestly wasn't expecting this. (I did this previously in java, and it behaves a little differently in this regard).
How will we get past this bug? Stay tuned!
The code for this project is available here on GitHub. I'll be updating it gradually as I write this series. I'll be sure to commit at least as often as I post, so you can back up and see that code as it was when I published a given post.
[EDIT]: The next post is now available here. Also, it just occured to me that these posts are themselves effectively a linked list. Meta!
Posted on November 26, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.