Re: Iterator instances not independent
Mats Wichmann <[email protected]> Mon, 8 Dec 2025 09:16:12 -0700
| Newsgroups | gmane.comp.python.tutor |
|---|---|
| Message-ID | <[email protected]> |
On 12/8/25 02:41, Sarfraaz Ahmed via Tutor wrote:
> for x in seqA:
> if (seqB.hasNext()):
> bStr = str(next(itB))
> else:
> bStr = "done"
> print("A =", next(itA), "B =", bStr)
> Hello Fran,
>
> My first guess is that the "for" loop is also doing a "next" on seqA (
> apart from the explicit next() in the print statement at the end of the
> loop )
Indeed, each time through the for loop consumes one item from the
iterator seqA - that's what iteration does - and then you additionally
consume another.
When you write a loop to iterate, you want to do something with the
values the iterator gives you, so the usual form is in pseudo-code:
for var in iterator:
do-something-with-var
You do nothing at all with 'x', so alternating values from seqA are just
lost.
You've understood some of the iteration protocol, as you're defining
__iter__ and __next__. But this is kind of the Hard Way, writing a
generator function is a lot easier - the use of the "yield" statement
makes it a generator, which suspends execution until the next attempt to
consume from it, so the context is there and you don't have to store
state variables in a class instance. And you don't have to provide a
function to query if the generator has more values to offer, because it
will automatically raise a StopExecption if it's out of values, which,
when iterating over it, just means "okay, we're done".
So a simple-minded rewrite of your Sequence could be something like:
def Sequence(last=10):
i = 0
while i < last:
yield i
i += 1
_______________________________________________
Tutor maillist - To unsubscribe send an email to [email protected]
To unsubscribe or change subscription options:
%(web_page_url)slistinfo/%(_internal_name)s