How to print the EXACT element of list node instead of its location


Hello, in this code I just made a list node and then tried to print all its elements, but instead the code prints the location of those elements. What is the fault? How do I code so that the exact element gets printed instead of its location

print(cu.val)?

1 Like

You need to implement the __str__ magic method for your Node class.

I tried that as well, it does not work

Since you didn’t provide an example of what you tried and just claimed “it did not work”, I also tried it, and it works as it is expected to work.

class Node:
    def __init__(self, val):
      self.val = val
      self.next = None

    def __str__(self):
        return f"Node value is {self.val}"

a = Node(str('A'))
b = Node(str('B'))
c = Node(str('C'))
d = Node(str('D'))

a.next = b
b.next = c
c.next = d

def pll(head):
    cu = head
    while cu !=	None:
        print(cu)
        cu = cu.next

pll(a)
kpfleming@balrog24:~$ python3 node_class.py
Node value is A
Node value is B
Node value is C
Node value is D
2 Likes