Attribute Error: 'NoneType' object has no attribute '_next'

Question:

I understand that these errors occur when plugging instance methods or any preset functions to None type, but since I’m implementing a singly Linked List I need to assign a None type to the last node. How do I resolve this issue since I can’t change the input value here.

Following is my code —

class singlyLinked:
    class _node:
        def __init__(self, data, next):
            self._data = data
            self._next = next
            
    def __init__(self):
        self._head=None
        self._tail=None
        self._size=0
    
    def __len__(self):
        return self._size
        
    def isEmpty(self):
        return self._size==0
    
    def first(self):
        if self.isEmpty():
            raise Error('Queue is Empty')
        return self._head._data #front aligned with the head of list
    
    def dequeue(self):
        if self.isEmpty():
            raise Error('Queue is Empty')
        answer=self._head._data
        self._head=self._head._next
        self._size -= 1
        if self.isEmpty():
            self._tail=None
        return answer
    
    def enqueue(self, e):
        newest=self._node(e, None)
        if self.isEmpty():
            self._head=newest
        else:
            self._tail._next=newest
        self.tail=newest
        self._size+=1

and I get the following error in Jupyter Notebook

AttributeError                            Traceback (most recent call last)
Cell In [20], line 3
      1 a=singlyLinked()
      2 a.enqueue(5)
----> 3 a.enqueue(5)
      4 a.enqueue(5)
      5 a.enqueue(5)

Cell In [19], line 41, in singlyLinked.enqueue(self, e)
     39     self._head=newest
     40 else:
---> 41     self._tail._next=newest
     42 self.tail=newest
     43 self._size+=1

AttributeError: 'NoneType' object has no attribute '_next'
Asked By: Aryan Arora

||

Answers:

You have a typo in

        newest=self._node(e, None)
        if self.isEmpty():
            self._head=newest
        else:
            self._tail._next=newest
        self.tail=newest
        self._size+=1

You need:

self._tail = newest (with underscore)

Answered By: svfat

You can change enqueue function to this:

    def enqueue(self, e):
        newest=self._node(e, None)
        if self.isEmpty():
            self._head=newest
            self._tail=newest
        else:
            self._tail._next=newest
            self._tail=newest
        self._size+=1

Answered By: imilano