SlideShare a Scribd company logo
Generators
Why generators?
● Writing memory optimized code.
● Understanding how Python web framework works. Eg: Django, Flask
● Writing simpler, abstracted code. We will see an example at the end.
What is a generator?
● Function
● Function having yield keyword
● Lazy evaluation
Example generator
In [65]: def example_generator(): # Is a function
...: yield 1 # Has **yield**
...: yield 2 # Can have more than 1 yield
...:
In [66]: for each in example_generator(): # Generator instances are mostly used
with for
...: print each
...:
Without generator
● Memory consuming code
● Custom implementation of range, custom_range()
● 4 million numbers would take ~ 100 MB
With generator
● Memory efficient code
● Custom implementation of xrange, custom_xrange().
● 4 million numbers would take 24 bytes
Generator control flow
● Execution suspends on encountering yield.
● Execution resumes with next iteration.
● Execution stops on encountering return.
Real world usage
● xrange()
● os.walk()
● File operations: Reading, searching etc.
● itertools.permutations()
Generators and Iterators
● Every generator is an iterator but not vice versa.
● Generator instances are iterables. They can be used with iter()
Recap
● Iterable must implement __iter__(). No need to implement next().
● Iterator must implement next(). No need to implement __iter__()
● iter() must be used with Iterable.
● next() must be used with iterator.
How for loop works
● **for** works with an iterable which must have an underlying iterator.
● iter(iterable) is called which returns a iterator.
● next() of iterator is repeatedly called until StopIteration is raised from next().
Why generator over iterators
● Generator functions are convenient shortcuts to build iterators.
● Generators remove boilerplate.
● Compare class xrange_iterator() with generator custom_xrange().
About me
http://agiliq.com
http://agiliq.com/blog
http://github.com/agiliq

More Related Content

PPTX
Python Functions
PPTX
Regular expressions in Python
PPTX
Iterarators and generators in python
ODP
Python Modules
PPTX
Fundamentals of Python Programming
PDF
Python Programming Language | Python Classes | Python Tutorial | Python Train...
PPTX
Generators In Python
Python Functions
Regular expressions in Python
Iterarators and generators in python
Python Modules
Fundamentals of Python Programming
Python Programming Language | Python Classes | Python Tutorial | Python Train...
Generators In Python

What's hot (20)

PPTX
Functions in python slide share
PPTX
String Builder & String Buffer (Java Programming)
PDF
Python functions
PDF
Methods in Java
PDF
Python - gui programming (tkinter)
PPS
Wrapper class
PDF
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
PPTX
Python Lambda Function
PDF
Strings in java
PPTX
Python basics
PDF
Python set
PPTX
Advanced Python : Decorators
PPTX
Java exception handling
PPT
SQLITE Android
PPTX
Basic Concepts of OOPs (Object Oriented Programming in Java)
PDF
Python programming : Strings
PDF
Python Flow Control
PDF
Python Collections Tutorial | Edureka
PDF
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
PPTX
Method overloading
Functions in python slide share
String Builder & String Buffer (Java Programming)
Python functions
Methods in Java
Python - gui programming (tkinter)
Wrapper class
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Python Lambda Function
Strings in java
Python basics
Python set
Advanced Python : Decorators
Java exception handling
SQLITE Android
Basic Concepts of OOPs (Object Oriented Programming in Java)
Python programming : Strings
Python Flow Control
Python Collections Tutorial | Edureka
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Method overloading
Ad

Similar to Python Generators (20)

PDF
SOSCON 2016 JerryScript
PPTX
Diagnosing HotSpot JVM Memory Leaks with JFR and JMC
PDF
Mirko Damiani - An Embedded soft real time distributed system in Go
PDF
Ruxmon.2013-08.-.CodeBro!
PDF
JRuby: Pushing the Java Platform Further
PDF
JerryScript: An ultra-lighteweight JavaScript Engine for the Internet of Things
PDF
Performance optimization techniques for Java code
PDF
Hunting and Exploiting Bugs in Kernel Drivers - DefCamp 2012
PPTX
Improving Kafka at-least-once performance at Uber
PDF
Reverse Engineering 101
PPTX
Helidon Nima - Loom based microserfice framework.pptx
PDF
Unmanned Aerial Vehicles: Exploit Automation with the Metasploit Framework
PDF
High performance json- postgre sql vs. mongodb
PDF
Jaime Peñalba - Kernel exploitation. ¿El octavo arte? [rooted2019]
PDF
Dfrws eu 2014 rekall workshop
PDF
Manticore 6.pdf
PDF
"Lightweight Virtualization with Linux Containers and Docker". Jerome Petazzo...
PPTX
Understanding eBPF in a Hurry!
PDF
AWS Lambdas are cool - Cheminfo Stories Day 1
KEY
OpenMP
SOSCON 2016 JerryScript
Diagnosing HotSpot JVM Memory Leaks with JFR and JMC
Mirko Damiani - An Embedded soft real time distributed system in Go
Ruxmon.2013-08.-.CodeBro!
JRuby: Pushing the Java Platform Further
JerryScript: An ultra-lighteweight JavaScript Engine for the Internet of Things
Performance optimization techniques for Java code
Hunting and Exploiting Bugs in Kernel Drivers - DefCamp 2012
Improving Kafka at-least-once performance at Uber
Reverse Engineering 101
Helidon Nima - Loom based microserfice framework.pptx
Unmanned Aerial Vehicles: Exploit Automation with the Metasploit Framework
High performance json- postgre sql vs. mongodb
Jaime Peñalba - Kernel exploitation. ¿El octavo arte? [rooted2019]
Dfrws eu 2014 rekall workshop
Manticore 6.pdf
"Lightweight Virtualization with Linux Containers and Docker". Jerome Petazzo...
Understanding eBPF in a Hurry!
AWS Lambdas are cool - Cheminfo Stories Day 1
OpenMP
Ad

Recently uploaded (20)

DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Electronic commerce courselecture one. Pdf
PDF
NewMind AI Monthly Chronicles - July 2025
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Encapsulation theory and applications.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
Cloud computing and distributed systems.
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
cuic standard and advanced reporting.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
The AUB Centre for AI in Media Proposal.docx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
MYSQL Presentation for SQL database connectivity
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Chapter 3 Spatial Domain Image Processing.pdf
Unlocking AI with Model Context Protocol (MCP)
Electronic commerce courselecture one. Pdf
NewMind AI Monthly Chronicles - July 2025
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Encapsulation theory and applications.pdf
Spectral efficient network and resource selection model in 5G networks
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Cloud computing and distributed systems.
Mobile App Security Testing_ A Comprehensive Guide.pdf
Encapsulation_ Review paper, used for researhc scholars
Understanding_Digital_Forensics_Presentation.pptx
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
cuic standard and advanced reporting.pdf
Review of recent advances in non-invasive hemoglobin estimation

Python Generators

  • 2. Why generators? ● Writing memory optimized code. ● Understanding how Python web framework works. Eg: Django, Flask ● Writing simpler, abstracted code. We will see an example at the end.
  • 3. What is a generator? ● Function ● Function having yield keyword ● Lazy evaluation
  • 4. Example generator In [65]: def example_generator(): # Is a function ...: yield 1 # Has **yield** ...: yield 2 # Can have more than 1 yield ...: In [66]: for each in example_generator(): # Generator instances are mostly used with for ...: print each ...:
  • 5. Without generator ● Memory consuming code ● Custom implementation of range, custom_range() ● 4 million numbers would take ~ 100 MB
  • 6. With generator ● Memory efficient code ● Custom implementation of xrange, custom_xrange(). ● 4 million numbers would take 24 bytes
  • 7. Generator control flow ● Execution suspends on encountering yield. ● Execution resumes with next iteration. ● Execution stops on encountering return.
  • 8. Real world usage ● xrange() ● os.walk() ● File operations: Reading, searching etc. ● itertools.permutations()
  • 9. Generators and Iterators ● Every generator is an iterator but not vice versa. ● Generator instances are iterables. They can be used with iter()
  • 10. Recap ● Iterable must implement __iter__(). No need to implement next(). ● Iterator must implement next(). No need to implement __iter__() ● iter() must be used with Iterable. ● next() must be used with iterator.
  • 11. How for loop works ● **for** works with an iterable which must have an underlying iterator. ● iter(iterable) is called which returns a iterator. ● next() of iterator is repeatedly called until StopIteration is raised from next().
  • 12. Why generator over iterators ● Generator functions are convenient shortcuts to build iterators. ● Generators remove boilerplate. ● Compare class xrange_iterator() with generator custom_xrange().