SlideShare a Scribd company logo
Iterator Protocol
Iterators and Iterables
Why iterator protocol?
● 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.
Iterator Protocol
Iterator Protocol needs two objects:
● Iterables
● Iterators
Iterables
● Any class which implements __iter__().
● Must implement __iter__().
● __iter__() **must** return an iterator.
Built in iter()
● Must be used with an iterable.
● Using with NotIterable() raises TypeError.
● Using with an Iterable() whose __iter__() doesn’t return iterator also raises
TypeError.
Example iterable
In [8]: class B(object):
...: def next(self):
...: return 5
In [9]: class A(object):
...: def __iter__(self): // __iter__() is implemented
...: return B() // __iter__() also returns an iterator.
Iterators
● Any class which implements next().
● Must implement next().
Built in next()
● Must be used with an iterator.
● Using with NotIterator() raises TypeError.
StopIteration
● Used inside next() of an Iterator.
● Used to signal that the iterator has been fully consumed.
StopIteration implementation
In [5]: class B(object):
...: def __init__(self):
...: self.i = 0
...: def next(self):
...: if self.i == 3:
...: raise StopIteration()
...: self.i += 1
...: return "boom"
Recap
● Iteraable 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().
How for loop works with Python lists
● A list is an iterable. It has __iter__.
● __iter__() of list returns an iterator. This iterator has next().
● Try next(list_iterator) and check it raises StopIteration.
Real world usage of iterator protocol
● Implementing xrange(). Memory optimized code.
● Implementing Fibonacci numbers upto a maximum.
● Django fields and forms.

More Related Content

PDF
Python Generators
PDF
Python intro
ODT
(3) cpp abstractions more_on_user_defined_types_exercises
PPTX
C++ metaprogramming
PPTX
Storage classes in c++
PPTX
Learning Python - Week 2
PDF
Gnu octave
PPTX
Storage class in C Language
Python Generators
Python intro
(3) cpp abstractions more_on_user_defined_types_exercises
C++ metaprogramming
Storage classes in c++
Learning Python - Week 2
Gnu octave
Storage class in C Language

What's hot (19)

PPTX
Storage classes in C
PPTX
Storage class
PPT
Storage classes
PPTX
Storage classes in C
PPT
Storage classes
PPTX
11 lec 11 storage class
PDF
Intro python-object-protocol
PPTX
Storage class in c
PPTX
Storage classes
PPTX
Storage classes
PPTX
Storage classes in c language
PPT
Core java day4
PDF
Fantom - Programming Language for JVM, CLR, and Javascript
PPT
Storage classes
PDF
Python master class part 1
PDF
Golang and Eco-System Introduction / Overview
PDF
COSCUP: Foreign Function Call in Julia
PDF
Method swizzling
PPTX
Storage Class in C Progrmming
Storage classes in C
Storage class
Storage classes
Storage classes in C
Storage classes
11 lec 11 storage class
Intro python-object-protocol
Storage class in c
Storage classes
Storage classes
Storage classes in c language
Core java day4
Fantom - Programming Language for JVM, CLR, and Javascript
Storage classes
Python master class part 1
Golang and Eco-System Introduction / Overview
COSCUP: Foreign Function Call in Julia
Method swizzling
Storage Class in C Progrmming
Ad

Similar to Iterator protocol (20)

PPTX
Iterarators and generators in python
PDF
Functional python
PPTX
Docketrun's Python Course for beginners.pptx
PPTX
Advance-Python-Iterators-for-developers.pptx
PPTX
python ppt.pptx
PPTX
Python Unit II.pptx
PDF
python interview prep question , 52 questions
PPTX
Python_UNIT-I.pptx
PPTX
08-Iterators-and-Generators.pptx
PPTX
Kotlin
PPTX
Generators & Decorators.pptx
PDF
Porting to Python 3
PPTX
Python advance
PDF
singh singhsinghsinghsinghsinghsinghsinghsinghsingh.pdf
PPT
Python advanced 1.handle error, generator, decorator and decriptor
PPTX
My Presentation ITPsdhjccjh cjhj (1).pptx
PPTX
My Presentation ITPdcjsdicjscisuchc.pptx
PDF
25 must know python for Interview by Tutort Academy
PDF
Introduction to Functional Programming
PPTX
Programming in C sesion 2
Iterarators and generators in python
Functional python
Docketrun's Python Course for beginners.pptx
Advance-Python-Iterators-for-developers.pptx
python ppt.pptx
Python Unit II.pptx
python interview prep question , 52 questions
Python_UNIT-I.pptx
08-Iterators-and-Generators.pptx
Kotlin
Generators & Decorators.pptx
Porting to Python 3
Python advance
singh singhsinghsinghsinghsinghsinghsinghsinghsingh.pdf
Python advanced 1.handle error, generator, decorator and decriptor
My Presentation ITPsdhjccjh cjhj (1).pptx
My Presentation ITPdcjsdicjscisuchc.pptx
25 must know python for Interview by Tutort Academy
Introduction to Functional Programming
Programming in C sesion 2
Ad

Recently uploaded (20)

PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
Cloud computing and distributed systems.
PPT
Teaching material agriculture food technology
PDF
Machine learning based COVID-19 study performance prediction
PDF
Encapsulation theory and applications.pdf
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Electronic commerce courselecture one. Pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
A Presentation on Artificial Intelligence
PDF
Approach and Philosophy of On baking technology
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
Machine Learning_overview_presentation.pptx
PDF
cuic standard and advanced reporting.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
Digital-Transformation-Roadmap-for-Companies.pptx
Cloud computing and distributed systems.
Teaching material agriculture food technology
Machine learning based COVID-19 study performance prediction
Encapsulation theory and applications.pdf
Dropbox Q2 2025 Financial Results & Investor Presentation
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Electronic commerce courselecture one. Pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
sap open course for s4hana steps from ECC to s4
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Review of recent advances in non-invasive hemoglobin estimation
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
A Presentation on Artificial Intelligence
Approach and Philosophy of On baking technology
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Machine Learning_overview_presentation.pptx
cuic standard and advanced reporting.pdf
20250228 LYD VKU AI Blended-Learning.pptx

Iterator protocol

  • 2. Why iterator protocol? ● 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. Iterator Protocol Iterator Protocol needs two objects: ● Iterables ● Iterators
  • 4. Iterables ● Any class which implements __iter__(). ● Must implement __iter__(). ● __iter__() **must** return an iterator.
  • 5. Built in iter() ● Must be used with an iterable. ● Using with NotIterable() raises TypeError. ● Using with an Iterable() whose __iter__() doesn’t return iterator also raises TypeError.
  • 6. Example iterable In [8]: class B(object): ...: def next(self): ...: return 5 In [9]: class A(object): ...: def __iter__(self): // __iter__() is implemented ...: return B() // __iter__() also returns an iterator.
  • 7. Iterators ● Any class which implements next(). ● Must implement next().
  • 8. Built in next() ● Must be used with an iterator. ● Using with NotIterator() raises TypeError.
  • 9. StopIteration ● Used inside next() of an Iterator. ● Used to signal that the iterator has been fully consumed.
  • 10. StopIteration implementation In [5]: class B(object): ...: def __init__(self): ...: self.i = 0 ...: def next(self): ...: if self.i == 3: ...: raise StopIteration() ...: self.i += 1 ...: return "boom"
  • 11. Recap ● Iteraable 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.
  • 12. 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().
  • 13. How for loop works with Python lists ● A list is an iterable. It has __iter__. ● __iter__() of list returns an iterator. This iterator has next(). ● Try next(list_iterator) and check it raises StopIteration.
  • 14. Real world usage of iterator protocol ● Implementing xrange(). Memory optimized code. ● Implementing Fibonacci numbers upto a maximum. ● Django fields and forms.