Categories: python

Generators in Python

Generator Function:

In Python, a generator is a function that allows you to create an iterator, an object that generates a sequence of values. A generator function is defined using the keyword yield, rather than return. When a generator function is called, it returns a generator object, which can be used to iterate over the sequence of values produced by the generator. The function’s code is not executed until the generator’s __next__() method is called, allowing the generator to produce a new value each time it is called. This allows for more memory-efficient and time-efficient operations for large data sets.

Here is an example of a generator function in Python:

def my_range(n):
    i = 0
    while i < n:
        yield i
        i += 1

for i in my_range(5):
    print(i)

In this example, my_range(n) is a generator function that generates the sequence of integers from 0 to n-1. The yield keyword is used to return the next value in the sequence, which is stored in the variable i. When the for loop iterates over the generator object returned by my_range(5), it will print the numbers 0 through 4.

Note that the generator function does not return a value, but instead yields values one at a time.

A generator function can also be used with the next() function, which retrieves the next item from the generator:

gen = my_range(5)
print(next(gen))
print(next(gen))

It will print 0 then 1

Also, it can be used with the iter() function

gen = iter(my_range(5))
print(next(gen))
print(next(gen))

It will also print 0 then 1

Generator Object:

A generator object is an iterator returned when a generator function is called. The generator object can be used to iterate over the sequence of values produced by the generator function. The __next__() method can be called on the generator object to retrieve the next value in the sequence.

The generator object also has an __iter__() method, which returns the generator object itself, making it an iterator. This allows the generator object to be used in a for loop, as well as in other contexts that expect an iterator.

Note: When the generator function reaches a return statement or the end of the function, a StopIteration exception is raised, signaling the end of the iteration.

A generator can be resumed by calling next() on it after it has stopped. However, it will start over from the beginning and not continue from where it stopped.

Here is an example of how to create a generator object:

def my_range(n):
    i = 0
    while i < n:
        yield i
        i += 1

gen = my_range(5)
print(next(gen))
print(next(gen))

The my_range function is defined as a generator function using the keyword yield to produce values. When called, it returns a generator object, which is stored in the variable gen. The next() function is used to retrieve the next value from the generator object, in this case, the first value is 0 then 1.

You can also use the generator object in a for loop

gen = my_range(5)
for i in gen:
    print(i)

This will print all the values of the generator object (0,1,2,3,4)

It’s worth noting that the generator object can only be iterated once, so when it reaches the end of the iteration, it throws the StopIteration exception.

Generator vs. Normal Function vs. Python List

A generator function is different from a normal function inpp that it uses the yield keyword to produce values, rather than the return keyword. A normal function will return a single value or a tuple of multiple values, while a generator function returns a generator object that can be used to iterate over a sequence of values.

A generator function is also different from a list in Python in that it does not generate all of the values at once. Instead, it generates values one at a time, only when they are needed. This makes generators more memory-efficient for large data sets.

A normal function will return the output value when it is called, it will use memory to store the results. But a generator function only generates the next value when it is called, it does not use memory to store the entire set of results.

Note: also read about yield Keyword in Python

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

3 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

2 years ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

2 years ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

2 years ago