1 of 4

Generator in Python

By

Mridusmita Baruah

Dept of CSE

GCU,Guwahati

2 of 4

What is Generator in Python

  • In Python, a generator is a way to create a sequence of values one at a time, as you need them, instead of all at once. This saves memory and is useful when working with large amounts of data.

  • Generator functions allow us to declare a function that behaves like an iterator, i.e. it can be used in a for loop. Instead of returning a single value like a regular function, a generator function yields a series of values, one at a time, pausing the function's state between each yield. This makes generators particularly useful for handling large datasets or streams of data efficiently.

3 of 4

Basic Generator Function

  • A generator function is defined like a regular function but uses the ‘yield’ statement instead of 'return'.

4 of 4

Example :

This example demonstrates how to create a simple generator that yields numbers from 1 to 5. The 'yield' statement allows the function to return a value and pause its state, making it efficient for iteration.

  • A simple generator function that yields numbers from 1 to 5

def simple_generator():

for i in range(1, 6): # Iterate from 1 to 5

yield i # Yield the current value of I

# Using the generator

gen = simple_generator()

# Iterating through the generator

for value in gen:

print(value)