Print is printing elements of linked list without loop

Advertisements

I am creating linked list. In my linked list i have str method in both classes Node and LinkedList. What i was trying to do is, print object in readable format whenever i print object to console. So i used str method in Node class, but i have no idea how this is printing all elements in the linked list without any loop whenever i use print() function.

class LinkedList:
    def __init__(self):
        self.head = None
    
    def __str__(self):
        if self.head is not None:
            return str(self.head)
        return 'empty linked list'
    
    def insert(self, data):
        if self.head is None:
            self.head = Node(data)
        else:
            head = self.head
            while head.next is not None:
                head = head.next
            head.next = Node(data)
        

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
    
    def __str__(self):
        return f"{self.data}\n{self.next}"
        
        
elems1 = [1,2,3,4]

llist1 = LinkedList()

for elem in elems1:
    llist1.insert(elem)
 
print(llist1)
    

I figured out that using {self.next} in str method in Node class is causing such behaviour but i have now idea how this is working.

>Solution :

Lets go down (or up if you prefer) the call stack.

  1. print(llist1) this calls the method LinkedList.__str__
  2. that LinkedList.__str__ then calls str(self.head) which then calls the method Node.__str__
  3. that Node.__str__ then returns the expression f"{self.data}\n{self.next}"
  4. in evaluating that expression, you then must call the self.next and then stringifyit. (putting that expression self.next in that f-string calls the __str__ method)
  5. so now you’ve called Node.__str__ on self.next which as we know will then call its self.next and so on and so on until self.next == None in which case there’s no more __str__ method to call
  6. self.next will return the empty string and stop the recursive call stack

You’ve created a recursive program without realizing it.

Leave a ReplyCancel reply