python generator object code example
Example 1: generator expressions python
>>> even_squares = (x * x for x in range(10)
if x % 2 == 0)
Example 2: python generator
def grepper_gen():
yield "add"
yield "grepper"
yield "answer"
grepper = grepper_gen()
next(grepper)
> add
next(grepper)
> grepper
next(grepper)
> answer
Example 3: python generators
import sys
n= 80000
a=[n**2 for n in range(n)]
b=(n**2 for n in range(n))
print(f"List: {sys.getsizeof(a)} bits\nGenerator: {sys.getsizeof(b)} bits")
Example 4: python generator
def count_to_ten_generator():
for number in range(10):
yield number
my_generator = count_to_ten_generator()
first_number = next(my_generator)
list_or_the_rest = list(my_generator)