I have a problem with my __iter__()
implementation for a Linked List structure. I wanted to implement it without using yield
and iter()
.
With one loop it works fine, but when I add a nested loop, the outer loop only iterates once and exits after the inner loop has finished:
class LinkedList:
class Node:
def __init__(self, data, next=None):
self.data, self.next = data, next
def __init__(self, seq=None):
self.head = self.tail = None
self.extend(seq)
self.current = self.head
def __iter__(self):
return self
def __next__(self):
if not self.current:
raise StopIteration
else:
temp = self.current.data
self.current = self.current.next
return iter(self.current)
def extend(self, seq):
for val in reversed(seq):
node = self.Node(val, self.head)
if self.tail is None:
self.tail = node
self.head = node
ll = LinkedList(range(10, 101, 10))
for val in ll:
for val2 in ll:
print((val, val2))
This produces the wrong output:
(10, 20) (10, 30) (10, 40) (10, 50) (10, 60) (10, 70) (10, 80) (10, 90) (10, 100)
While I expect to also get tuples where the first value is 20, 30, ...etc.