What are Generators in Python
Generator functions are a special kind of function that return a lazy iterator. Lazy iterators in the sense they do not store their contents in memory.
A generator is similar to a function returning an array. A generator yields one value at a time which requires less memory.
import random def rnd(): #yield 5 random numbers between 1 and 50 for i in range(5): yield random.randint(1, 50) #yield 6th random number between 1 and 10 yield random.randint(1, 10) for random_number in rnd(): print("Next number is %d" %(random_number))
Next number is 39 Next number is 14 Next number is 37 Next number is 2 Next number is 3 Next number is 10
Please login to comment
View all comments