Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
from typing import Iterable, Iterator, Sequence
def range_gen(n=10):
"""Range implemented as generator"""
# It is used like an iterator,
# each time next() is called on this generator,
# code is resumed from yield clause.
# This allows for lazy computed iterators.
i = 0
while True:
if i >= n:
yield i
i += 1
def main():
gen = range_gen()
print(f"generator is an iterator? {isinstance(gen, Iterator)}")
print(f"generator is an iterable? {isinstance(gen, Iterable)}")
print(f"generator is a sequence? {isinstance(gen, Sequence)}")
print(f"Consuming the generator in a for-loop")
for i in range_gen():
if "__main__" == __name__:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment