Why Is This Listiterator Stuck?
childGenerator()
method returns an iterator
object via python's built in iter()
function. An iterator has a .next()
method which returns the next item or raises StopIteration
when it runs out of elements.An enumerator is a special kind of iterator. It also has a .next()
method, but instead of returning just the next value, it returns a tuple containing a count and the next value.
Your for loop takes two arguments (i
and each
) and so the python interpreter expects the iterator to supply a two-element tuple. If you only pass in the iterator supplied by childGenerator()
, python only has one element available instead of the two that it needs and chokes. However, if you create an enumerator from the iterator via enumerate()
, then the interpreter gets the two-element tuple it requires.
Solution 2:
gnibbler is correct in explaining that you could only consume generators once. Just to expound further:
According to the docs an iterator
is an object representing a stream of data. Since you already consumed the stream (i.e you reach the end of the stream), reiterating over it will not yield any data. I had the same problem before but Karl Knechtel's comment cleared things up for me. Hope my explanation is clear.
Post a Comment for "Why Is This Listiterator Stuck?"