Search code examples
pythondata-structureslinked-listnonetype

'NoneType' object has no attribute 'element'


why in the code below when printing head.element inside the while loop I dont get any error but the same code print code outside the loop get me an error?

class node:
  def __init__(self, element):
        self.element = element
        self.next = None


head = None

node1 = node(1)
node2 = node(2)

head = node1
node1.next = node2

while head != None:
    print(head.element)
    head = head.next

print(head.element)

Solution

  • The error is raised by your last line of code:

    print(head.element)
    

    when/if the flow reaches the line above, the head variable is None, since the while loop ends only when head == None.

    while head != None:
        print(head.element)
        head = head.next # The last time this will return None