0% found this document useful (0 votes)
2 views6 pages

Understanding Generator Functions and Objects

Generator functions use the yield keyword to produce a generator object, which can be iterated using the next method or a for loop. They are particularly useful for creating streams of data, such as Fibonacci numbers, and for processing large data files efficiently. This approach allows for handling data in a memory-efficient manner by processing only parts of the data at a time.

Uploaded by

NUSRAT HUSSAIN
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views6 pages

Understanding Generator Functions and Objects

Generator functions use the yield keyword to produce a generator object, which can be iterated using the next method or a for loop. They are particularly useful for creating streams of data, such as Fibonacci numbers, and for processing large data files efficiently. This approach allows for handling data in a memory-efficient manner by processing only parts of the data at a time.

Uploaded by

NUSRAT HUSSAIN
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Generator

• Generator-Function : A generator-function is defined like a normal function, but whenever it


needs to generate a value, it does so with the yield keyword rather than return. If the body of a
def contains yield, the function automatically becomes a generator function.
Generator
Generator
• Generator-Object : Generator functions return a generator object. Generator objects are used
either by calling the next method on the generator object or using the generator object in a “for
in” loop
Generator
Generator
Applications
• To create a stream of Fibonacci numbers, adopting the generator approach makes it trivial; we just
have to call next(x) to get the next Fibonacci number without bothering about where or when the
stream of numbers ends.
• A more practical type of stream processing is handling large data files such as log files.
• Generators provide a space efficient method for such data processing as only parts of the file are
handled at one given point in time.

You might also like