SlideShare a Scribd company logo
1 of 29
https://softuni.org
Software University
Technical Trainers
SoftUni Team
Definitions, Implementations and Examples
Iterators and Generators
2
1. What are Iterators?
 Loops and Iterators
2. What are Generators?
 The yield Statement
 Generators and Functions
 Generator Expressions
Table of Contents
3
sli.do
#python-advanced
Have a Question?
__iter__() and __next__()
What are Iterators?
4
 Iterator is simply an object that can be iterated upon
 An object which will return data, one element at a
time
 Iterator object must implement two methods,
__iter__() and __next__() (iterator protocol)
 An object is called iterable if we can get an iterator
from it
 Such are: list, tuple, string, etc...
What are Iterators?
6
my_list = [4, 7, 0, 3]
# get an iterator using iter()
my_iter = iter(my_list)
print(next(my_iter)) # 4
print(next(my_iter)) # 7
print(my_iter.__next__()) # 0
print(my_iter.__next__()) # 3
next(my_iter) # Error
 The iter() function (which in turn calls the __iter__()
method) returns an iterator from an iterable
Example: Iterator
7
iter_obj = iter(iterable)
while True:
try:
element = next(iter_obj) # get the next item
# do something with element
except StopIteration:
# if StopIteration is raised, break from loop
break
 The for loop can iterate automatically through the list
 The for loop can iterate over any iterable
 A for loop is implemented as:
For Loops and Iterators
8
 The for loop creates an iterator object, iter_obj by calling
iter() on the iterable
 Inside the loop, it calls next() to get the next element and
executes the body of the for loop with this value
 After all the items exhaust, StopIteration is raised which is
internally caught and the loop ends
Explanation
9
one_to_ten = custom_range(1, 10)
for num in one_to_ten:
print(num)
 Since iterators are implemented using classes, create a class
called custom_range that receives start and end upon
initialization
 Implement the __iter__ and __next__ methods, so the
iterator returns the numbers from the start to the end
Problem: Custom Range
1
2
…
10
10
class custom_range:
def __init__(self, start, end):
self.i = start
self.n = end
def __iter__(self):
return self
def __next__(self):
if self.i <= self.n:
i = self.i
self.i += 1
return i
else:
raise StopIteration()
Solution: Custom Range
11
reversed_list = reverse_iter([1, 2, 3, 4])
for item in reversed_list:
print(item)
 Create a class called reverse_iter which should receive an
iterable upon initialization
 Implement the __iter__ and __next__ methods, so the
iterator returns the items of the iterable in reversed order
Problem: Reverse Iter
4
3
2
1
12
class reverse_iter:
def __init__(self, iterable):
self.iterable = iterable
self.i = len(self.iterable) - 1
self.j = 0
def __iter__(self):
return self
def __next__(self):
# TODO: Implement
Solution: Reverse Iter
Way of Creating Iterators
What are Generators?
1
 Generators are a simple way of creating iterators
 A generator is a function that returns an object
(iterator)
 This iterator can later be iterated over (one value at a
time)
What are Generators?
15
def first_n(n):
num = 0
while num < n:
yield num
num += 1
sum_first_n = sum(first_n(5))
print(sum_first_n)
Example: Generators
16
 If a function contains at least one yield statement, it
becomes a generator function
 Both yield and return will return a value from a
function
 The difference between yield and return is that the
return statement terminates a function entirely
 Yield however pauses the function saving all its states
and later continues from there on successive calls
The yield Statement
17
 Generator function contains one or more yield
statements
 It returns an iterator but does not start execution
immediately
 Methods like __iter__() and __next__() are
implemented automatically
 Once the function yields, the function is paused
 When the function terminates, StopIteration is
raised automatically on further calls
Generators vs Normal Functions
18
def my_gen():
n = 1
print('This is printed first')
yield n
n += 1
print('This is printed second')
yield n
n += 1
print('This is printed at last')
yield n
Example: Generator Function
The value of "n" is
remembered between calls
19
 Generators can be easily created using generator
expressions
 Same as lambda function creates an anonymous
function, generator expression creates an
anonymous generator function
 The syntax for generator expression is similar to that
of a list comprehension
 The difference between them is that generator
expression produces one item at a time
Generator Expression
20
# Initialize the list
my_list = [1, 3, 6, 10]
# square each term using list comprehension
# Output: [1, 9, 36, 100]
[x**2 for x in my_list]
# same thing can be done using generator expression
# Output: <generator object <genexpr> at 0x0000000002EBDAF8>
(x**2 for x in my_list)
Example: Generator Expression
21
print(list(squares(5)))
 Create a generator function called squares that should
receive a number n
 It should generate the squares of all numbers from 1 to n
Problem: Squares
[1, 4, 9, 16, 25]
def squares(n):
i = 1
while i <= n:
yield i * i
i += 1
22
print(list(genrange(1, 10)))
 Create a generator function called genrange that receives a
start and an end
 It should generate all the numbers from the start to the end
Problem: Generator Range
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
23
def genrange(start, end):
i = start
n = end
while i <= n:
yield i
i += 1
Solution: Generator Range
24
Summary
 Iterator is an object that can be iterated
upon
 Functions that returns iterators is called
generators
 Generators - yield, Functions - return
 Generator expression is like a list
comprehension
© SoftUni – https://softuni.org. Copyrighted document. Unauthorized copy, reproduction or use is not permitted.
© SoftUni – https://softuni.org. Copyrighted document. Unauthorized copy, reproduction or use is not permitted.
26
SoftUni Diamond Partners
27
SoftUni Organizational Partners
28
 This course (slides, examples, demos, exercises, homework,
documents, videos and other assets) is copyrighted content
 Unauthorized copy, reproduction or use is illegal
 © SoftUni – https://softuni.org
 © Software University – https://softuni.bg
License
29
 Software University – High-Quality Education,
Profession and Job for Software Developers
 softuni.bg, softuni.org
 Software University Foundation
 softuni.foundation
 Software University @ Facebook
 facebook.com/SoftwareUniversity
 Software University Forums
 forum.softuni.bg
Trainings @ Software University (SoftUni)

More Related Content

Similar to 08-Iterators-and-Generators.pptx

Elegant Solutions for Everyday Python Problems Pycon 2018 - Nina Zakharenko
Elegant Solutions for Everyday Python Problems Pycon 2018 - Nina ZakharenkoElegant Solutions for Everyday Python Problems Pycon 2018 - Nina Zakharenko
Elegant Solutions for Everyday Python Problems Pycon 2018 - Nina ZakharenkoNina Zakharenko
 
Generators & Decorators.pptx
Generators & Decorators.pptxGenerators & Decorators.pptx
Generators & Decorators.pptxIrfanShaik98
 
C++ Course - Lesson 2
C++ Course - Lesson 2C++ Course - Lesson 2
C++ Course - Lesson 2Mohamed Ahmed
 
Python programing
Python programingPython programing
Python programinghamzagame
 
Python lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce functionPython lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce functionARVIND PANDE
 
Python_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptxPython_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptxSahajShrimal1
 
Python functions
Python functionsPython functions
Python functionsToniyaP1
 
Very basic functional design patterns
Very basic functional design patternsVery basic functional design patterns
Very basic functional design patternsTomasz Kowal
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdfprasnt1
 
Recursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & StructureRecursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & Structurecogaxor346
 
Python Exam (Questions with Solutions Done By Live Exam Helper Experts)
Python Exam (Questions with Solutions Done By Live Exam Helper Experts)Python Exam (Questions with Solutions Done By Live Exam Helper Experts)
Python Exam (Questions with Solutions Done By Live Exam Helper Experts)Live Exam Helper
 
Bottom of FormCreate your own FunctionFunctionsFor eac.docx
Bottom of FormCreate your own FunctionFunctionsFor eac.docxBottom of FormCreate your own FunctionFunctionsFor eac.docx
Bottom of FormCreate your own FunctionFunctionsFor eac.docxAASTHA76
 
Modules in Python.docx
Modules in Python.docxModules in Python.docx
Modules in Python.docxmanohar25689
 
ForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptxForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptxAaliyanShaikh
 
Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )Ziyauddin Shaik
 

Similar to 08-Iterators-and-Generators.pptx (20)

Elegant Solutions for Everyday Python Problems Pycon 2018 - Nina Zakharenko
Elegant Solutions for Everyday Python Problems Pycon 2018 - Nina ZakharenkoElegant Solutions for Everyday Python Problems Pycon 2018 - Nina Zakharenko
Elegant Solutions for Everyday Python Problems Pycon 2018 - Nina Zakharenko
 
Generators & Decorators.pptx
Generators & Decorators.pptxGenerators & Decorators.pptx
Generators & Decorators.pptx
 
C++ Course - Lesson 2
C++ Course - Lesson 2C++ Course - Lesson 2
C++ Course - Lesson 2
 
Python programing
Python programingPython programing
Python programing
 
Python lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce functionPython lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce function
 
Python_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptxPython_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptx
 
Python functions
Python functionsPython functions
Python functions
 
Very basic functional design patterns
Very basic functional design patternsVery basic functional design patterns
Very basic functional design patterns
 
Lecture 8.pdf
Lecture 8.pdfLecture 8.pdf
Lecture 8.pdf
 
functions
functionsfunctions
functions
 
Functions2.pptx
Functions2.pptxFunctions2.pptx
Functions2.pptx
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
 
Recursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & StructureRecursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & Structure
 
Python Exam (Questions with Solutions Done By Live Exam Helper Experts)
Python Exam (Questions with Solutions Done By Live Exam Helper Experts)Python Exam (Questions with Solutions Done By Live Exam Helper Experts)
Python Exam (Questions with Solutions Done By Live Exam Helper Experts)
 
Bottom of FormCreate your own FunctionFunctionsFor eac.docx
Bottom of FormCreate your own FunctionFunctionsFor eac.docxBottom of FormCreate your own FunctionFunctionsFor eac.docx
Bottom of FormCreate your own FunctionFunctionsFor eac.docx
 
Modules in Python.docx
Modules in Python.docxModules in Python.docx
Modules in Python.docx
 
Functions.pdf
Functions.pdfFunctions.pdf
Functions.pdf
 
Functionscs12 ppt.pdf
Functionscs12 ppt.pdfFunctionscs12 ppt.pdf
Functionscs12 ppt.pdf
 
ForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptxForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptx
 
Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )
 

Recently uploaded

Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 

Recently uploaded (20)

Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 

08-Iterators-and-Generators.pptx

  • 1. https://softuni.org Software University Technical Trainers SoftUni Team Definitions, Implementations and Examples Iterators and Generators
  • 2. 2 1. What are Iterators?  Loops and Iterators 2. What are Generators?  The yield Statement  Generators and Functions  Generator Expressions Table of Contents
  • 5.  Iterator is simply an object that can be iterated upon  An object which will return data, one element at a time  Iterator object must implement two methods, __iter__() and __next__() (iterator protocol)  An object is called iterable if we can get an iterator from it  Such are: list, tuple, string, etc... What are Iterators?
  • 6. 6 my_list = [4, 7, 0, 3] # get an iterator using iter() my_iter = iter(my_list) print(next(my_iter)) # 4 print(next(my_iter)) # 7 print(my_iter.__next__()) # 0 print(my_iter.__next__()) # 3 next(my_iter) # Error  The iter() function (which in turn calls the __iter__() method) returns an iterator from an iterable Example: Iterator
  • 7. 7 iter_obj = iter(iterable) while True: try: element = next(iter_obj) # get the next item # do something with element except StopIteration: # if StopIteration is raised, break from loop break  The for loop can iterate automatically through the list  The for loop can iterate over any iterable  A for loop is implemented as: For Loops and Iterators
  • 8. 8  The for loop creates an iterator object, iter_obj by calling iter() on the iterable  Inside the loop, it calls next() to get the next element and executes the body of the for loop with this value  After all the items exhaust, StopIteration is raised which is internally caught and the loop ends Explanation
  • 9. 9 one_to_ten = custom_range(1, 10) for num in one_to_ten: print(num)  Since iterators are implemented using classes, create a class called custom_range that receives start and end upon initialization  Implement the __iter__ and __next__ methods, so the iterator returns the numbers from the start to the end Problem: Custom Range 1 2 … 10
  • 10. 10 class custom_range: def __init__(self, start, end): self.i = start self.n = end def __iter__(self): return self def __next__(self): if self.i <= self.n: i = self.i self.i += 1 return i else: raise StopIteration() Solution: Custom Range
  • 11. 11 reversed_list = reverse_iter([1, 2, 3, 4]) for item in reversed_list: print(item)  Create a class called reverse_iter which should receive an iterable upon initialization  Implement the __iter__ and __next__ methods, so the iterator returns the items of the iterable in reversed order Problem: Reverse Iter 4 3 2 1
  • 12. 12 class reverse_iter: def __init__(self, iterable): self.iterable = iterable self.i = len(self.iterable) - 1 self.j = 0 def __iter__(self): return self def __next__(self): # TODO: Implement Solution: Reverse Iter
  • 13. Way of Creating Iterators What are Generators? 1
  • 14.  Generators are a simple way of creating iterators  A generator is a function that returns an object (iterator)  This iterator can later be iterated over (one value at a time) What are Generators?
  • 15. 15 def first_n(n): num = 0 while num < n: yield num num += 1 sum_first_n = sum(first_n(5)) print(sum_first_n) Example: Generators
  • 16. 16  If a function contains at least one yield statement, it becomes a generator function  Both yield and return will return a value from a function  The difference between yield and return is that the return statement terminates a function entirely  Yield however pauses the function saving all its states and later continues from there on successive calls The yield Statement
  • 17. 17  Generator function contains one or more yield statements  It returns an iterator but does not start execution immediately  Methods like __iter__() and __next__() are implemented automatically  Once the function yields, the function is paused  When the function terminates, StopIteration is raised automatically on further calls Generators vs Normal Functions
  • 18. 18 def my_gen(): n = 1 print('This is printed first') yield n n += 1 print('This is printed second') yield n n += 1 print('This is printed at last') yield n Example: Generator Function The value of "n" is remembered between calls
  • 19. 19  Generators can be easily created using generator expressions  Same as lambda function creates an anonymous function, generator expression creates an anonymous generator function  The syntax for generator expression is similar to that of a list comprehension  The difference between them is that generator expression produces one item at a time Generator Expression
  • 20. 20 # Initialize the list my_list = [1, 3, 6, 10] # square each term using list comprehension # Output: [1, 9, 36, 100] [x**2 for x in my_list] # same thing can be done using generator expression # Output: <generator object <genexpr> at 0x0000000002EBDAF8> (x**2 for x in my_list) Example: Generator Expression
  • 21. 21 print(list(squares(5)))  Create a generator function called squares that should receive a number n  It should generate the squares of all numbers from 1 to n Problem: Squares [1, 4, 9, 16, 25] def squares(n): i = 1 while i <= n: yield i * i i += 1
  • 22. 22 print(list(genrange(1, 10)))  Create a generator function called genrange that receives a start and an end  It should generate all the numbers from the start to the end Problem: Generator Range [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  • 23. 23 def genrange(start, end): i = start n = end while i <= n: yield i i += 1 Solution: Generator Range
  • 24. 24 Summary  Iterator is an object that can be iterated upon  Functions that returns iterators is called generators  Generators - yield, Functions - return  Generator expression is like a list comprehension
  • 25. © SoftUni – https://softuni.org. Copyrighted document. Unauthorized copy, reproduction or use is not permitted. © SoftUni – https://softuni.org. Copyrighted document. Unauthorized copy, reproduction or use is not permitted.
  • 28. 28  This course (slides, examples, demos, exercises, homework, documents, videos and other assets) is copyrighted content  Unauthorized copy, reproduction or use is illegal  © SoftUni – https://softuni.org  © Software University – https://softuni.bg License
  • 29. 29  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg, softuni.org  Software University Foundation  softuni.foundation  Software University @ Facebook  facebook.com/SoftwareUniversity  Software University Forums  forum.softuni.bg Trainings @ Software University (SoftUni)