SlideShare a Scribd company logo
1 of 22
Iterator Pattern
Damian Gordon
Iterator Pattern
• The iterator pattern is a design pattern in which an iterator is
used to traverse a container and access the container's
elements.
Iterator Pattern
• The iterator pattern is a design pattern in which an iterator is
used to traverse a container and access the container's
elements.
Iterator Pattern
• The iterator pattern is a design pattern in which an iterator is
used to traverse a container and access the container's
elements.
Iterator Pattern
• The iterator pattern is a design pattern in which an iterator is
used to traverse a container and access the container's
elements.
Iterator Pattern
• The iterator pattern is a design pattern in which an iterator is
used to traverse a container and access the container's
elements.
Iterator Pattern
• The iterator pattern is a design pattern in which an iterator is
used to traverse a container and access the container's
elements.
Iterator Pattern
• The iterator pattern is a design pattern in which an iterator is
used to traverse a container and access the container's
elements.
Iterator Pattern
• The iterator pattern is a design pattern in which an iterator is
used to traverse a container and access the container's
elements.
Iterator Pattern
• In a programming language without patterns, an
iterator would have a next() method and a done()
method, and the iterator loops across all the containers
using these methods.
Iterator Pattern
• In a programming language without patterns, an
iterator would have a next() method and a done()
method, and the iterator loops across all the containers
using these methods.
WHILE NOT(iterator.done())
DO item = iterator.next()
# do more stuff
ENDWHILE;
Iterator Pattern
• The iterator pattern in Python has the following features:
Name Description
_ _next_ _() The next method returns the next
element from the container.
StopIteration() The StopIteration is an exception
that is raised when the last element is
reached.
_ _iter_ _() The iter method makes the object
iterable, and returns an iterator.
Iterator Pattern
• The iterator pattern has two parts:
–An iterable class (to create the iterator object)
–An iterator class (to traverse a container)
def __init__(self, VALUE):
self.VALUE = VALUE
# END Init
def __iter__(self):
return ITERATOR(self.VALUE)
# END Iter
class ITERABLE:
# END ITERABLE.
def __init__(self, VALUE):
self.VALUE = VALUE
self.index = 0
# END Init
def __iter__(self):
return self
# END Iter
def __next__(self):
if CONDITION:
VALUE = SELF.VALUE
self.index = self.index + 1
return VALUE
else:
raise StopIteration()
# ENDIF;
# END Next
class ITERATOR:
# END ITERATOR.
Iterator Pattern
• Let’s look at a simple example that counts numbers,
there’ll be three parts:
– The Iterable part
– The Iteration part
– The program execution part
Iterator Pattern
class MyCountIterable:
def __init__(self, Value):
self.Value = Value
# END Init
def __iter__(self):
return MyCountIteration(self.Value)
# END Iter
# END MyCountIterable.
Iterator Pattern
class MyCountIteration:
def __init__(self, Value):
self.Index = 0
self.Value = Value
# END Init
def __iter__(self):
# Iterators are iterables too.
return self
# END Iter
def __next__(self):
if self.Index < self.Value:
# THEN
Index = self.Index
self.Index += 1
return Index
else:
raise StopIteration()
# ENDIF;
# END Next
# END MyCountIteration.
Iterator Pattern
FirstCount = MyCountIterable(5)
list(FirstCount)
FirstCountIter = iter(FirstCount)
while True:
# DO
try:
print(next(FirstCountIter))
except StopIteration:
break
# ENDWHILE
Iterator Pattern
FirstCount = MyCountIterable(5)
list(FirstCount)
FirstCountIter = iter(FirstCount)
while True:
# DO
try:
print(next(FirstCountIter))
except StopIteration:
break
# ENDWHILE
0
1
2
3
4
Iterator Pattern
• Hang on…
• Couldn’t we just do:
• YES!
for Counter in range(0,5):
print(Counter)
# ENDFOR;
etc.

More Related Content

What's hot (20)

Functions in Python
Functions in PythonFunctions in Python
Functions in Python
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Vector class in C++
Vector class in C++Vector class in C++
Vector class in C++
 
Junit
JunitJunit
Junit
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
 
Oops concept on c#
Oops concept on c#Oops concept on c#
Oops concept on c#
 
Jquery library
Jquery libraryJquery library
Jquery library
 
Iterator Design Pattern
Iterator Design PatternIterator Design Pattern
Iterator Design Pattern
 
An Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysAn Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: Arrays
 
Refactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerRefactoring Tips by Martin Fowler
Refactoring Tips by Martin Fowler
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
 
Python SQite3 database Tutorial | SQlite Database
Python SQite3 database Tutorial | SQlite DatabasePython SQite3 database Tutorial | SQlite Database
Python SQite3 database Tutorial | SQlite Database
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
 
Jpa 잘 (하는 척) 하기
Jpa 잘 (하는 척) 하기Jpa 잘 (하는 척) 하기
Jpa 잘 (하는 척) 하기
 
TDD in Python With Pytest
TDD in Python With PytestTDD in Python With Pytest
TDD in Python With Pytest
 
Introduction to java and oop
Introduction to java and oopIntroduction to java and oop
Introduction to java and oop
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 
Clean code slide
Clean code slideClean code slide
Clean code slide
 
Iterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design patternIterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design pattern
 
OOP-Advanced Programming with c++
OOP-Advanced Programming with c++OOP-Advanced Programming with c++
OOP-Advanced Programming with c++
 

Viewers also liked

Introduction to Python programming
Introduction to Python programmingIntroduction to Python programming
Introduction to Python programmingDamian T. Gordon
 
Python: Multiple Inheritance
Python: Multiple InheritancePython: Multiple Inheritance
Python: Multiple InheritanceDamian T. Gordon
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and PackagesDamian T. Gordon
 
Python: Third-Party Libraries
Python: Third-Party LibrariesPython: Third-Party Libraries
Python: Third-Party LibrariesDamian T. Gordon
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in PythonDamian T. Gordon
 
Python: Migrating from Procedural to Object-Oriented Programming
Python: Migrating from Procedural to Object-Oriented ProgrammingPython: Migrating from Procedural to Object-Oriented Programming
Python: Migrating from Procedural to Object-Oriented ProgrammingDamian T. Gordon
 
The Extreme Programming (XP) Model
The Extreme Programming (XP) ModelThe Extreme Programming (XP) Model
The Extreme Programming (XP) ModelDamian T. Gordon
 

Viewers also liked (13)

Object-Orientated Design
Object-Orientated DesignObject-Orientated Design
Object-Orientated Design
 
Introduction to Python programming
Introduction to Python programmingIntroduction to Python programming
Introduction to Python programming
 
Python: Multiple Inheritance
Python: Multiple InheritancePython: Multiple Inheritance
Python: Multiple Inheritance
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
 
Python: Basic Inheritance
Python: Basic InheritancePython: Basic Inheritance
Python: Basic Inheritance
 
Python: Design Patterns
Python: Design PatternsPython: Design Patterns
Python: Design Patterns
 
Python: Third-Party Libraries
Python: Third-Party LibrariesPython: Third-Party Libraries
Python: Third-Party Libraries
 
Python: Access Control
Python: Access ControlPython: Access Control
Python: Access Control
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in Python
 
Python: Manager Objects
Python: Manager ObjectsPython: Manager Objects
Python: Manager Objects
 
Python: Polymorphism
Python: PolymorphismPython: Polymorphism
Python: Polymorphism
 
Python: Migrating from Procedural to Object-Oriented Programming
Python: Migrating from Procedural to Object-Oriented ProgrammingPython: Migrating from Procedural to Object-Oriented Programming
Python: Migrating from Procedural to Object-Oriented Programming
 
The Extreme Programming (XP) Model
The Extreme Programming (XP) ModelThe Extreme Programming (XP) Model
The Extreme Programming (XP) Model
 

Similar to Python: The Iterator Pattern

Similar to Python: The Iterator Pattern (7)

Spl to the Rescue - Zendcon 09
Spl to the Rescue - Zendcon 09Spl to the Rescue - Zendcon 09
Spl to the Rescue - Zendcon 09
 
SPL to the Rescue - Tek 09
SPL to the Rescue - Tek 09SPL to the Rescue - Tek 09
SPL to the Rescue - Tek 09
 
Java tutorial part 3
Java tutorial part 3Java tutorial part 3
Java tutorial part 3
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Introduction to OOP in Python
Introduction to OOP in PythonIntroduction to OOP in Python
Introduction to OOP in Python
 
Intro
IntroIntro
Intro
 
Iterarators and generators in python
Iterarators and generators in pythonIterarators and generators in python
Iterarators and generators in python
 

More from Damian T. Gordon

Universal Design for Learning, Co-Designing with Students.
Universal Design for Learning, Co-Designing with Students.Universal Design for Learning, Co-Designing with Students.
Universal Design for Learning, Co-Designing with Students.Damian T. Gordon
 
Introduction to Microservices
Introduction to MicroservicesIntroduction to Microservices
Introduction to MicroservicesDamian T. Gordon
 
Introduction to Cloud Computing
Introduction to Cloud ComputingIntroduction to Cloud Computing
Introduction to Cloud ComputingDamian T. Gordon
 
Evaluating Teaching: SECTIONS
Evaluating Teaching: SECTIONSEvaluating Teaching: SECTIONS
Evaluating Teaching: SECTIONSDamian T. Gordon
 
Evaluating Teaching: MERLOT
Evaluating Teaching: MERLOTEvaluating Teaching: MERLOT
Evaluating Teaching: MERLOTDamian T. Gordon
 
Evaluating Teaching: Anstey and Watson Rubric
Evaluating Teaching: Anstey and Watson RubricEvaluating Teaching: Anstey and Watson Rubric
Evaluating Teaching: Anstey and Watson RubricDamian T. Gordon
 
Designing Teaching: Pause Procedure
Designing Teaching: Pause ProcedureDesigning Teaching: Pause Procedure
Designing Teaching: Pause ProcedureDamian T. Gordon
 
Designing Teaching: ASSURE
Designing Teaching: ASSUREDesigning Teaching: ASSURE
Designing Teaching: ASSUREDamian T. Gordon
 
Designing Teaching: Laurilliard's Learning Types
Designing Teaching: Laurilliard's Learning TypesDesigning Teaching: Laurilliard's Learning Types
Designing Teaching: Laurilliard's Learning TypesDamian T. Gordon
 
Designing Teaching: Gagne's Nine Events of Instruction
Designing Teaching: Gagne's Nine Events of InstructionDesigning Teaching: Gagne's Nine Events of Instruction
Designing Teaching: Gagne's Nine Events of InstructionDamian T. Gordon
 
Designing Teaching: Elaboration Theory
Designing Teaching: Elaboration TheoryDesigning Teaching: Elaboration Theory
Designing Teaching: Elaboration TheoryDamian T. Gordon
 
Universally Designed Learning Spaces: Some Considerations
Universally Designed Learning Spaces: Some ConsiderationsUniversally Designed Learning Spaces: Some Considerations
Universally Designed Learning Spaces: Some ConsiderationsDamian T. Gordon
 

More from Damian T. Gordon (20)

Universal Design for Learning, Co-Designing with Students.
Universal Design for Learning, Co-Designing with Students.Universal Design for Learning, Co-Designing with Students.
Universal Design for Learning, Co-Designing with Students.
 
Introduction to Microservices
Introduction to MicroservicesIntroduction to Microservices
Introduction to Microservices
 
REST and RESTful Services
REST and RESTful ServicesREST and RESTful Services
REST and RESTful Services
 
Serverless Computing
Serverless ComputingServerless Computing
Serverless Computing
 
Cloud Identity Management
Cloud Identity ManagementCloud Identity Management
Cloud Identity Management
 
Containers and Docker
Containers and DockerContainers and Docker
Containers and Docker
 
Introduction to Cloud Computing
Introduction to Cloud ComputingIntroduction to Cloud Computing
Introduction to Cloud Computing
 
Introduction to ChatGPT
Introduction to ChatGPTIntroduction to ChatGPT
Introduction to ChatGPT
 
How to Argue Logically
How to Argue LogicallyHow to Argue Logically
How to Argue Logically
 
Evaluating Teaching: SECTIONS
Evaluating Teaching: SECTIONSEvaluating Teaching: SECTIONS
Evaluating Teaching: SECTIONS
 
Evaluating Teaching: MERLOT
Evaluating Teaching: MERLOTEvaluating Teaching: MERLOT
Evaluating Teaching: MERLOT
 
Evaluating Teaching: Anstey and Watson Rubric
Evaluating Teaching: Anstey and Watson RubricEvaluating Teaching: Anstey and Watson Rubric
Evaluating Teaching: Anstey and Watson Rubric
 
Evaluating Teaching: LORI
Evaluating Teaching: LORIEvaluating Teaching: LORI
Evaluating Teaching: LORI
 
Designing Teaching: Pause Procedure
Designing Teaching: Pause ProcedureDesigning Teaching: Pause Procedure
Designing Teaching: Pause Procedure
 
Designing Teaching: ADDIE
Designing Teaching: ADDIEDesigning Teaching: ADDIE
Designing Teaching: ADDIE
 
Designing Teaching: ASSURE
Designing Teaching: ASSUREDesigning Teaching: ASSURE
Designing Teaching: ASSURE
 
Designing Teaching: Laurilliard's Learning Types
Designing Teaching: Laurilliard's Learning TypesDesigning Teaching: Laurilliard's Learning Types
Designing Teaching: Laurilliard's Learning Types
 
Designing Teaching: Gagne's Nine Events of Instruction
Designing Teaching: Gagne's Nine Events of InstructionDesigning Teaching: Gagne's Nine Events of Instruction
Designing Teaching: Gagne's Nine Events of Instruction
 
Designing Teaching: Elaboration Theory
Designing Teaching: Elaboration TheoryDesigning Teaching: Elaboration Theory
Designing Teaching: Elaboration Theory
 
Universally Designed Learning Spaces: Some Considerations
Universally Designed Learning Spaces: Some ConsiderationsUniversally Designed Learning Spaces: Some Considerations
Universally Designed Learning Spaces: Some Considerations
 

Recently uploaded

An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfSanaAli374401
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterMateoGardella
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.MateoGardella
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...KokoStevan
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 

Recently uploaded (20)

INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 

Python: The Iterator Pattern

  • 2. Iterator Pattern • The iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements.
  • 3. Iterator Pattern • The iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements.
  • 4. Iterator Pattern • The iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements.
  • 5. Iterator Pattern • The iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements.
  • 6. Iterator Pattern • The iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements.
  • 7. Iterator Pattern • The iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements.
  • 8. Iterator Pattern • The iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements.
  • 9. Iterator Pattern • The iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements.
  • 10. Iterator Pattern • In a programming language without patterns, an iterator would have a next() method and a done() method, and the iterator loops across all the containers using these methods.
  • 11. Iterator Pattern • In a programming language without patterns, an iterator would have a next() method and a done() method, and the iterator loops across all the containers using these methods. WHILE NOT(iterator.done()) DO item = iterator.next() # do more stuff ENDWHILE;
  • 12. Iterator Pattern • The iterator pattern in Python has the following features: Name Description _ _next_ _() The next method returns the next element from the container. StopIteration() The StopIteration is an exception that is raised when the last element is reached. _ _iter_ _() The iter method makes the object iterable, and returns an iterator.
  • 13. Iterator Pattern • The iterator pattern has two parts: –An iterable class (to create the iterator object) –An iterator class (to traverse a container)
  • 14. def __init__(self, VALUE): self.VALUE = VALUE # END Init def __iter__(self): return ITERATOR(self.VALUE) # END Iter class ITERABLE: # END ITERABLE.
  • 15. def __init__(self, VALUE): self.VALUE = VALUE self.index = 0 # END Init def __iter__(self): return self # END Iter def __next__(self): if CONDITION: VALUE = SELF.VALUE self.index = self.index + 1 return VALUE else: raise StopIteration() # ENDIF; # END Next class ITERATOR: # END ITERATOR.
  • 16. Iterator Pattern • Let’s look at a simple example that counts numbers, there’ll be three parts: – The Iterable part – The Iteration part – The program execution part
  • 17. Iterator Pattern class MyCountIterable: def __init__(self, Value): self.Value = Value # END Init def __iter__(self): return MyCountIteration(self.Value) # END Iter # END MyCountIterable.
  • 18. Iterator Pattern class MyCountIteration: def __init__(self, Value): self.Index = 0 self.Value = Value # END Init def __iter__(self): # Iterators are iterables too. return self # END Iter def __next__(self): if self.Index < self.Value: # THEN Index = self.Index self.Index += 1 return Index else: raise StopIteration() # ENDIF; # END Next # END MyCountIteration.
  • 19. Iterator Pattern FirstCount = MyCountIterable(5) list(FirstCount) FirstCountIter = iter(FirstCount) while True: # DO try: print(next(FirstCountIter)) except StopIteration: break # ENDWHILE
  • 20. Iterator Pattern FirstCount = MyCountIterable(5) list(FirstCount) FirstCountIter = iter(FirstCount) while True: # DO try: print(next(FirstCountIter)) except StopIteration: break # ENDWHILE 0 1 2 3 4
  • 21. Iterator Pattern • Hang on… • Couldn’t we just do: • YES! for Counter in range(0,5): print(Counter) # ENDFOR;
  • 22. etc.