Skip to content

Instantly share code, notes, and snippets.

@Nimamoh
Created October 19, 2021 20:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nimamoh/3d00d92a30810d562c1a21666768f979 to your computer and use it in GitHub Desktop.
Save Nimamoh/3d00d92a30810d562c1a21666768f979 to your computer and use it in GitHub Desktop.
generator.py
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:
break
yield i
i += 1
def main():
gen = range_gen()
print(type(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():
print(i)
if "__main__" == __name__:
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment