Why Does A Python Iterator Need A Dunder Iter Function?
According to the documentation, a container that needs to be iterable should supply an __iter__() function to return an iterator. The iterator itself is required to follow the iter
Solution 1:
Iterators needs to be iterable to support for-loops and iter().
This lead to: Why one would want to iterate over an iterator?
Because sometimes you're directly given iterators, for example an opened file or a generator function:
>>>defgen():...yield1...yield2...>>>it = gen()>>>hasattr(it, '__next__')
True
This lead to: Why some parts of Python returns an interator instead of an iterable?
This is a way to tell the thing is "not rewindable" / "one-shot iterable". As returning an iterable would say "You can call iter() twice on it to iterate twice over it", which would be wrong.
Post a Comment for "Why Does A Python Iterator Need A Dunder Iter Function?"