Q:

python generator

# A generator-function is defined like a normal function, 
# but whenever it needs to generate a value, 
# it does so with the yield keyword rather than return. 
# If the body of a def contains yield, 
# the function automatically becomes a generator function.
# Python 3 example
def grepper_gen():
  yield "add"
  yield "grepper"
  yield "answer"
grepper = grepper_gen()
next(grepper)
> add
next(grepper)
> grepper
next(grepper)
> answer
10
# A Python program to generate squares from 1 
# to 100 using yield and therefore generator 
  
# An infinite generator function that prints 
# next square number. It starts with 1 
def nextSquare(): 
    i = 1; 
  
    # An Infinite loop to generate squares  
    while True: 
        yield i*i                 
        i += 1  # Next execution resumes  
                # from this point      
  
# Driver code to test above generator  
# function 
for num in nextSquare(): 
    if num > 100: 
         break    
    print(num) 
4
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)
-1

New to Communities?

Join the community