Exploring Python Generators
Join the DZone community and get the full member experience.
Join For Free
Generators in Python are literators they produce data one element at a time. Generators are memory efficient. They don’t store the entire sequence upfront, making them ideal for large datasets. This emphasizes its ability to handle potentially infinite or very large sequences without memory limitations.Â
They are created using a special kind of function known as the generator function, which contains one or more ‘yield’ statements. The yield statement produces a value and temporarily suspends the generator function’s execution, allowing it to be resumed later.
import random
def generate_random():
while True:
yield random.randint(1, 100)
gen = generate_random()
next(gen) //return some random value.
import random
def gen_seq():
print(‘yield 1’)
yield 1
print(‘yield 2’)
yield 2
gen = gen_seq()
next(gen) // prints yield 1 and return 1
next(gen) // prints yield 2 and return 2
numbers = [1,2,3,4]
gen_exp = (num for num in numbers)
next(gen_exp) //1
next(gen_exp) //2