
The Empty Second Loop
The star-charters built a Constellation class. The first loop over it works,
but every loop after that is mysteriously empty. Even worse, a nested loop
(pairing each star with each other star) stops after the first row.
Why?
Constellation returns self from __iter__, so the constellation is its
own iterator. There's only one position counter, so once it reaches the end,
it stays there.
The fix is to keep these two roles separate:
- A container (an iterable, like a list) should hand out a brand-new
iterator every time
__iter__is called. - Only one-shot iterators should return
self.
The easiest fix is to borrow a fresh iterator from the list you already store:
def __iter__(self):
return iter(self.items)
Assignment
Fix Constellation so it can be looped over any number of times, including
in nested loops. (__next__ and the index counter are no longer needed.)
Fix Constellation so it can be looped over any number of times, including
in nested loops. (__next__ and the index counter are no longer needed.)
Press Run to try your code, then Check to test it.