python generators medium.com code example

Example: python generators medium.com

>>>def gen_squares(iterable):>>>    for each in iterable:>>>        print (f'Here comes the square of {each}')>>>        yield each*each>>>        print (f'moving on  {each}')        >>>counter = gen_squares([1,2,3,4,5]) #generator was created, but is        #idle no memory usage until next() is called inside list().>>>print(counter)    <generator object gen_squares at 0x7f2dc8aaaa00>>>>print(next(counter))    Here comes the square of 1    1>>>print(next(counter))    moving on  1    Here comes the square of 2    4>>>print(next(counter))    moving on  2    Here comes the square of 3    9>>>print(next(counter))    moving on  3    Here comes the square of 4    16>>>print(next(counter))    moving on  4    Here comes the square of 5    25>>>print(list(counter))    Traceback (most recent call last):      File "main.py", line 17, in <module>        print(next(counter))    StopIteration>>>counter2 = gen_squares([1,2,3,4,5])>>>print(next(counter2))    Here comes the square of 1    1>>>print(list(counter2))    moving on  1    Here comes the square of 2    moving on  2    Here comes the square of 3    moving on  3    Here comes the square of 4    moving on  4    Here comes the square of 5    moving on  5    [4, 9, 16, 25]

Tags:

Misc Example