Use case

  • Reduce the memory usage
def square_calculator():
	i = 0
	while i < 10:
		yield i * i
		i++

if name == '__main__':
	for i in square_calculator():
		print(result)

The generator function can exit and re-enter the context with binding variables. So it’s known as lazy-evaluation, call when needed. square_calculator() here is an iterator and be called when the loop trigger it each time. The returned variable in the previous call in the memory storage can be released without waiting to return as an array like a normal function.

The generator function is already supported in so many languages such as Python, Javascript or Java as well.