Kinchit
Kinchit

Reputation: 23

LinkedList object is not iterable - Python - 'LinkedList' object is not iterable

class Node():
    def __init__(self, val, next=None):
        self.val = val
        self.next = next
        
        
    def __str__(self):
        return self.val
    
    
class LinkedList():
    def __init__(self):
        self.head = None
        
    
    def __repr__(self):
        node = self.head
        nodes = []
        while node is not None:
            nodes.append(node.val)
            node = node.next
        nodes.append("None")
        return "->".join(nodes)
    
    
    def add_first(self, node):
        if not self.head:
            self.head = node
        else:
            node.next = head
            self.head = node
    
    def add_last(self, node):
        if not self.head:
            self.head = node
            return
        else:
            curr = self.head
            while curr.next != None:
                curr = curr.next
            curr.next = node
            
    def add_before(self, target_data, node):
        if self.head.val == target_data:
            node.next = head
            self.head = node
        else:
            prev_node = self.head
            for node in self:
                if node.val == target_data:
                    prev_node.next = new_node
                    new_node.next = node
                    return
                prev_node = node
            

if __name__ == "__main__":
    llist = LinkedList()

    first = Node('a')
    llist.head = first

    second = Node('b')
    first.next = second

    third = Node('c')

    print(llist)
    llist.add_last(third)

    print(llist)
    llist.add_before("b", Node('d'))
    
    print(llist)

Error: for node in self: TypeError: 'LinkedList' object is not iterable

Can someone help me understand the problem and how to solve it? Trying to understand and solve the issue

Upvotes: 1

Views: 2220

Answers (1)

Andrew Guy
Andrew Guy

Reputation: 9968

This is the offending line:

for node in self:

This tries to iterate over the object instance, but you haven't defined this behaviour for the LinkedList class.

All iteratable objects in Python must have the __iter__() method defined. The Python wiki has more details on this, and the difference between an iterable and an iterator.

If you actually need this behaviour for this LinkedList class, you should implement the __iter__() method with appropriate logic.

Upvotes: 1

Related Questions