Screwing Up looping in Generator
Matt Wheeler
m at funkyhat.org
Tue Jan 3 04:46:56 EST 2017
On Tue, 3 Jan 2017 at 20:17 Deborah Swanson <python at deborahswanson.net> wrote:
> > What's the code for your generator? And I don't see where you
> > call 'next'.
>
> I think you're expecting
>
> for file in rootobs
>
> to get the next yield for you from rootobs, but unless someone corrects
> me, I don't think you can expect a 'for' statement to do that. You need
> to have a 'next' statement inside your for loop to get the next yield
> from the generator.
>
Yes, you absolutely can expect a for statement to do that. It will accept any
iterable as its `y`.
`for x in y: stuff(x)` is effectively syntactic sugar for:
iterator = iter(y)
while True:
try:
x = next(iterator)
except(StopIteration):
break
stuff(x)
Manually calling `next()` inside a `while True:` is quite an unusual thing to
do.
range() is not part of the for syntax at all, it's completely separate, it
simply returns an iterator which the for loop can use, like any other.
--
--
Matt Wheeler
http://funkyh.at
More information about the Python-list
mailing list