How to format the output print statement to print linked list?

So I trying to print the linked list after the string but I not able to do it.
The print statement is in pop function inside unordered class

The linked list always get printed first and then the string

54 26 56 93 17 77 31 7
Original Linked List: None

My Desired Output

Original Linked List: 54 26 56 93 17 77 31 7

class Node:
    def __init__(self, initdata): = initdata = None

    def getData(self):

    def getNext(self):

    def setData(self,newdata): = newdata

    def setNext(self,newnext): = newnext

class UnorderedList:

    def __init__(self):
        self.head = None

    def isEmpty(self):
        return self.head == None

    def printList(self):
        temp = self.head
        while (temp):
            print(, end=" ")
            temp =

    def pop(self):
        print('Original Linked List:' self.printList())
        current = self.head
        previous = None
        while current.getNext() != None:
            previous = current
            current = current.getNext()
        print('New linked list after pop is:', self.printList())

So I have tried formatting it with

print(f'Orginal Linked List: {self.printList()})
print('Original Linked List: %d' %(self.printList()))

Nothing really works
I am new to programming
I appreciate your help.

>Solution :

You need a function that returns a list rather than printing a list. It’s easiest if you name this function __str__ because then it’ll get called automatically whenever anything tries to convert your list to a string.


    def printList(self):
        temp = self.head
        while (temp):
            print(, end=" ")
            temp =


    def __str__(self):
        s = ''
        temp = self.head
        while temp:
            s += str( + " "
            temp =
        return s[:-1]

and then you can do:

print(f'Original Linked List: {self})

which will automatically call your __str__ method and put the result into the f-string.

Leave a Reply