0

I'm learning linked lists and to print it, my instructor used the following code but didn't explain it:

def __iter__(self):
    node = self.head
    while node:
        yield node
        node = node.next

print([node.value for node in singlyLinkedList])

I'm confused why 'while node' works and 'while True' throws an error.

VRM
  • 83
  • 1
  • 7
  • 1
    I would start by asking your instructor. That's what s/he is being paid for. – DYZ May 12 '22 at 06:03
  • 1
    Does this answer your question? [What is Truthy and Falsy? How is it different from True and False?](https://stackoverflow.com/questions/39983695/what-is-truthy-and-falsy-how-is-it-different-from-true-and-false) – DYZ May 12 '22 at 06:03

1 Answers1

0

This is checking that node exists before accessing it. It is then being set as the next object and continuing till it reaches null - then the while loop ends and data printed. If we were to set it to while true instead, we would follow the same logic, except eventually we will be trying to access the 'next' attribute for a null node. For linked lists, the final values 'next' attribute is null.

Thomas
  • 1
  • 2