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
Generators In Python
PPTX
PPTX
Iterarators and generators in python
PPTX
Tuple in python
PPTX
Looping statement in python
PPTX
Basics of Object Oriented Programming in Python
PPTX
Data Structures in Python
PPTX
Object oriented programming in python
Generators In Python
Iterarators and generators in python
Tuple in python
Looping statement in python
Basics of Object Oriented Programming in Python
Data Structures in Python
Object oriented programming in python

What's hot (20)

PPSX
python Function
PDF
Introduction to advanced python
PPTX
Python Functions
PPSX
Modules and packages in python
PDF
F strings
PDF
Python functions
PPTX
Python Lambda Function
PDF
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
PPTX
Python Exception Handling
PPTX
Python: Modules and Packages
PPTX
Object Oriented Programming in Python
PPTX
Functions in python slide share
PPTX
List in Python
PDF
Arrays in python
PPTX
Functions in python
PPTX
PHP Cookies and Sessions
PDF
Python programming : Control statements
PPT
Python ppt
PPTX
python Function
Introduction to advanced python
Python Functions
Modules and packages in python
F strings
Python functions
Python Lambda Function
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Python Exception Handling
Python: Modules and Packages
Object Oriented Programming in Python
Functions in python slide share
List in Python
Arrays in python
Functions in python
PHP Cookies and Sessions
Python programming : Control statements
Python ppt
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)

PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
PPTX
Big Data Technologies - Introduction.pptx
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
Cloud computing and distributed systems.
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PDF
Sensors and Actuators in IoT Systems using pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
Telecom Fraud Prevention Guide | Hyperlink InfoSystem
PDF
cuic standard and advanced reporting.pdf
PDF
Empathic Computing: Creating Shared Understanding
PPT
Teaching material agriculture food technology
PDF
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Big Data Technologies - Introduction.pptx
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
NewMind AI Weekly Chronicles - August'25 Week I
Dropbox Q2 2025 Financial Results & Investor Presentation
Diabetes mellitus diagnosis method based random forest with bat algorithm
Cloud computing and distributed systems.
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
GamePlan Trading System Review: Professional Trader's Honest Take
Sensors and Actuators in IoT Systems using pdf
Chapter 3 Spatial Domain Image Processing.pdf
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Telecom Fraud Prevention Guide | Hyperlink InfoSystem
cuic standard and advanced reporting.pdf
Empathic Computing: Creating Shared Understanding
Teaching material agriculture food technology
How Onsite IT Support Drives Business Efficiency, Security, and Growth.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().