-3
class Node:
def __init__(self,cargo = None, next = None):
    self.cargo = cargo
    self.next = next
    
def __str__(self):
    return str(self.cargo)

def printList(node):
    Nide = [node]
    while node:
        node = node.next
        Nide.append(node)
    print(str(Nide))

node1 = Node(1)
node2 = Node(2)
node3 = Node(3) 
node1.next = node2
node2.next = node3
node1.printList()

I am unable to properly collect list data(it should be in format of [1,2,3])

[<__main__.Node object at 0x0000012C08495FD0>, <__main__.Node object at 0x0000012C08495F10>, <__main__.Node object at 0x0000012C08495E20>, None]

I keep getting it like this.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Newbie
  • 1
  • 1

1 Answers1

0

list.__str__ displays the elements repr representation. So you should either add a __repr__ method to your Node class or (better) just add the node's cargo to the helper list:

def printList(node):
    Nide = []
    while node:
        Nide.append(node.cargo)  # add cargo only!
        node = node.next
    print(str(Nide))

This also fixes the None at the end of your list.

user2390182
  • 72,016
  • 6
  • 67
  • 89