Home > Net >  'NoneType' object has no attribute 'value'
'NoneType' object has no attribute 'value'

Time:09-24

when deleting the entire linked list using the "delete_entire(self)" method. It throws no attribute error. Although the above code is running fine. Instead of printing the blank list, it is giving the no attribute error.

class Node:
    def __init__(self,value):
        self.value = value
        self.next = None
    
class CircularSinglyLinkedList:
    def __init__(self):
        self.head = None
        self.tail = None
        
    

    def __iter__(self):
        node = self.head
        
        while True:
            yield node
            if node.next is self.head:
                break
            node = node.next
        
    

    def insertion(self, value, location):
    
        new_node = Node(value)
    
        if self.head is None:
            self.head = new_node
            self.tail = new_node
            self.tail.next = self.head
    
        else:
        
            if location == 0:
            
                new_node.next = self.head
                self.head = new_node
                self.tail.next = new_node
            
            elif location == -1:
                self.tail.next = new_node
                new_node.next = self.head
                self.tail = new_node
            
            else:
            
                temp_node = self.head
                index = 0
                while index < location -1:
                
                    if temp_node.next is self.head:
                        break
                    
                    temp_node = temp_node.next
                    index  = 1
            
                next_node = temp_node.next
                temp_node.next = new_node
                new_node.next = next_node
            
                if new_node.next is self.head:
                    self.tail = new_node
               
#---------------------------------------------------------------------------------------------#

    # deleting the entire linked list

    def delete_entire(self):
        self.head = None
        self.tail.next = None
        self.tail = None 




cll = CircularSinglyLinkedList()
cll.insertion(2,1)
cll.insertion(3,2)
cll.insertion(5,3)
cll.insertion(6,4)
cll.insertion(0,0)
cll.insertion(10,-1)
print([node.value for node in call])

output = [0, 2, 3, 5, 6, 10]

cll.delete_entire()
print([node.value for node in call])

AttributeError: 'NoneType' object has no attribute 'value'

The expected output is to be

[ ]

CodePudding user response:

Your __iter__() method always yields once, even when the list is empty, since it does yield node before checking whether node is None. Whenthe list is empty, that will yield None, and the caller will try to use None.value.

You should stop the loop as soon as node is None.

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