SlideShare ist ein Scribd-Unternehmen logo
1 von 28
Click to add Title
e-Infochips Institute of Training Research and Academics Limited
Iterators and Generators
Prepared by:
Pranali Patel
Kalindi Vora
Agenda
• Iterators
• Iteration protocol
• Infinite iterators
• Generators
• Generator expressions
• Relationship between iterator and generator
• Advantages
Iterators
• An iterator is an object which allows a programmer to traverse
through all the elements of a collection, regardless of its
specific implementation.
• An iterator is an object which implements the iterator
protocol.
• The iterator protocol consists of two methods:
• The __iter__() method which must return the iterator object
and next() method which returns the next element of sequence.
Examples
We use for statement for looping over a list.
>>> for i in [1, 2, 3, 4]:
... print i,
...
1
2
3
4
Examples
If we use it with a string, it loops over its characters.
>>> for c in "python":
... print c
...
p
y
t
h
o
n
Examples
If we use it with a dictionary, it loops over its keys.
>>> for k in {"x": 1, "y": 2}:
... print k
...
y
x
Examples
If we use it with a file, it loops over lines of the file.
>>> for line in open("a.txt"):
... print line,
...
first line
second line
Iteration protocol
• The built-in function iter takes an iterable object and returns an
iterator.
• Each time we call the next method on the iterator gives us the
next element.
• If there are no more elements, it raises a StopIteration.
Examples
>>> x = iter([1, 2, 3])
>>> x
<listiterator object at 0x1004ca850>
>>> x.next()
1
>>> x.next()
2
>>> x.next()
3
>>> x.next()
Traceback (most recent call last):
File <stdin>, line 1, in <module>
StopIteration
Examples
class yrange:
def __init__(self, n):
self.i = 0
self.n = n
def __iter__(self):
return self
def next(self):
if self.i < self.n:
i = self.i
self.i += 1
return i
else:
raise StopIteration()
Iterators are implemented as classes.
Here is an iterator that works like built-
in xrange function.
Examples
• The __iter__ method is what makes an object iterable.
• Behind the scenes, the iter function calls __iter__ method on
the given object.
• The return value of __iter__ is an iterator.
• It should have a next method and raise StopIteration when there
are no more elements.
Examples
>>> y = yrange(3)
>>> y.next()
0
>>> y.next()
1
>>> y.next()
2
>>> y.next()
Traceback (most recent call last):
File <stdin>, line 1, in <module>
File <stdin>, line 14, in next
StopIteration
Infinite Iterators
• It is not necessary that the item in an iterator object has to
exhaust.
• There can be infinite iterators (which never ends).
• We must be careful when handling such iterator.
Examples
>>> a = iter(InfIter())
>>> next(a)
1
>>> next(a)
3
>>> next(a)
5
>>> next(a)
7
class InfIter:
"""Infinite iterator to return all odd numbers"""
def __iter__(self):
self.num = 1
return self
def __next__(self):
num = self.num
self.num += 2
return num
Generators
• Generators simplifies creation of iterators.
• A generator is a function that produces a sequence of results
instead of a single value.
• A generator is a special routine that can be used to control the
iteration behaviour of a loop.
• A generator is similar to a function returning an array.
• A generator has parameters, it can be called and it generates a
sequence of result.
• But unlike functions, which return a whole array, a
generator yields one value at a time.
Generators
Generators in Python:
• Are defined with the def keyword
• Use the yield keyword
• May use several yield keywords
• Return an iterator
Examples
def yrange(n):
i = 0
while i < n:
yield i
i += 1
Each time the yield statement is executed the function
generates a new value.
Examples
>>> y = yrange(3)
>>> y
<generator object yrange at 0x401f30>
>>> y.next()
0
>>> y.next()
1
>>> y.next()
2
>>> y.next()
Traceback (most recent call last):
File <stdin>, line 1, in <module>
StopIteration
Examples
• A generator is also an iterator.
• The word “generator” is confusingly used to mean both the
function that generates and what it generates.
• When a generator function is called, it returns a generator
object without even beginning execution of the function.
• When next method is called for the first time, the function
starts executing until it reaches yield statement.
• The yielded value is returned by the next call.
Examples
>>> def foo():
... print "begin"
... for i in range(3):
... print "before yield", i
... yield i
... print "after yield", i
... print "end"
... >>> f = foo()
>>> f.next()
begin before yield 0
0
>>> f.next()
after yield 0
before yield 1
1
>>> f.next()
after yield 1
before yield 2
2
>>> f.next()
after yield 2
end
Traceback (most recent call last):
File <stdin>, line 1, in <module>
StopIteration
>>>
Examples
• Lets say we want to write a program that takes a list of filenames as
arguments and prints contents of all those files.
• The traditional way to implement it is:
def cat(filenames):
for f in filenames:
for line in open(f):
print line,
Examples
• Now, lets say we want to print only the line which has a
particular substring.
def grep(pattern, filenames):
for f in filenames:
for line in open(f):
if pattern in line:
print line,
• Both these programs have lot of code in common. It is hard to
move the common part to a function. But with generators makes
it possible to do it.
Examples
def readfiles(filenames):
for f in filenames:
for line in open(f):
yield line
def grep(pattern, lines):
return (line for line in lines if
pattern in line)
def printlines(lines):
for line in lines:
print line,
def main(pattern, filenames):
lines = readfiles(filenames)
lines = grep(pattern, lines)
printlines(lines)
Generator expressions
• There are two types of generators in Python:
generator functions and generator expressions.
• A generator function is any function in which the keyword yield
appears in its body.
• The appearance of the keyword yield is enough to make the
function a generator function.
• The other type of generators are the generator equivalent of a
list comprehension. Its syntax is really elegant for a limited use
case.
Examples
>>> numbers = [1, 2, 3, 4, 5, 6]
>>> [x * x for x in numbers]
[1, 4, 9, 16, 25, 36]
You could do the same thing with a set comprehension:
>>> {x * x for x in numbers}
{1, 4, 36, 9, 16, 25}
Or a dict comprehension:
>>> {x: x * x for x in numbers}
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}
Relationship between Generator and Iterator
Advantages
• Cleaner code
• Iterators can work with infinite sequences
• Iterators save resources
• Generator allows to write streaming code with fewer
intermediate variables and data structures.
• Memory and CPU efficient
THANK YOU

Weitere ähnliche Inhalte

Was ist angesagt?

Data types in python
Data types in pythonData types in python
Data types in pythonRaginiJain21
 
Python decorators
Python decoratorsPython decorators
Python decoratorsAlex Su
 
Map, Filter and Reduce In Python
Map, Filter and Reduce In PythonMap, Filter and Reduce In Python
Map, Filter and Reduce In PythonSimplilearn
 
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...Edureka!
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and PackagesDamian T. Gordon
 
File handling in Python
File handling in PythonFile handling in Python
File handling in PythonMegha V
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Edureka!
 
Functions in python
Functions in pythonFunctions in python
Functions in pythoncolorsof
 

Was ist angesagt? (20)

Java Streams
Java StreamsJava Streams
Java Streams
 
Data types in python
Data types in pythonData types in python
Data types in python
 
Python Modules
Python ModulesPython Modules
Python Modules
 
Python decorators
Python decoratorsPython decorators
Python decorators
 
Loops in Python
Loops in PythonLoops in Python
Loops in Python
 
Map, Filter and Reduce In Python
Map, Filter and Reduce In PythonMap, Filter and Reduce In Python
Map, Filter and Reduce In Python
 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
 
Namespaces
NamespacesNamespaces
Namespaces
 
Recursion in c++
Recursion in c++Recursion in c++
Recursion in c++
 
List in Python
List in PythonList in Python
List in Python
 
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
 
Advanced Python : Decorators
Advanced Python : DecoratorsAdvanced Python : Decorators
Advanced Python : Decorators
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
 
Python recursion
Python recursionPython recursion
Python recursion
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Python : Regular expressions
Python : Regular expressionsPython : Regular expressions
Python : Regular expressions
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
 
Set methods in python
Set methods in pythonSet methods in python
Set methods in python
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 

Ähnlich wie Iterarators and generators in python

python ppt.pptx
python ppt.pptxpython ppt.pptx
python ppt.pptxMONAR11
 
Python Programming unit5 (1).pdf
Python Programming unit5 (1).pdfPython Programming unit5 (1).pdf
Python Programming unit5 (1).pdfjamvantsolanki
 
Generators & Decorators.pptx
Generators & Decorators.pptxGenerators & Decorators.pptx
Generators & Decorators.pptxIrfanShaik98
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3Ahmet Bulut
 
Functions_21_22.pdf
Functions_21_22.pdfFunctions_21_22.pdf
Functions_21_22.pdfpaijitk
 
An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : PythonRaghu Kumar
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdfDaddy84
 
Python Learn Function with example programs
Python Learn Function with example programsPython Learn Function with example programs
Python Learn Function with example programsGeethaPanneer
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answerskavinilavuG
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answersRojaPriya
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...Maulik Borsaniya
 
Pythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptxPythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptxleavatin
 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.supriyasarkar38
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methodsPranavSB
 

Ähnlich wie Iterarators and generators in python (20)

python ppt.pptx
python ppt.pptxpython ppt.pptx
python ppt.pptx
 
Python Programming unit5 (1).pdf
Python Programming unit5 (1).pdfPython Programming unit5 (1).pdf
Python Programming unit5 (1).pdf
 
Generators & Decorators.pptx
Generators & Decorators.pptxGenerators & Decorators.pptx
Generators & Decorators.pptx
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3
 
Functions_21_22.pdf
Functions_21_22.pdfFunctions_21_22.pdf
Functions_21_22.pdf
 
Functions2.pptx
Functions2.pptxFunctions2.pptx
Functions2.pptx
 
Functions.pdf
Functions.pdfFunctions.pdf
Functions.pdf
 
Functionscs12 ppt.pdf
Functionscs12 ppt.pdfFunctionscs12 ppt.pdf
Functionscs12 ppt.pdf
 
An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : Python
 
Functions-.pdf
Functions-.pdfFunctions-.pdf
Functions-.pdf
 
Clojure intro
Clojure introClojure intro
Clojure intro
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
 
Python Learn Function with example programs
Python Learn Function with example programsPython Learn Function with example programs
Python Learn Function with example programs
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
 
Pythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptxPythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptx
 
Python_UNIT-I.pptx
Python_UNIT-I.pptxPython_UNIT-I.pptx
Python_UNIT-I.pptx
 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methods
 

Kürzlich hochgeladen

REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxannathomasp01
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17Celine George
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxUmeshTimilsina1
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 

Kürzlich hochgeladen (20)

REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 

Iterarators and generators in python

  • 1. Click to add Title e-Infochips Institute of Training Research and Academics Limited Iterators and Generators Prepared by: Pranali Patel Kalindi Vora
  • 2. Agenda • Iterators • Iteration protocol • Infinite iterators • Generators • Generator expressions • Relationship between iterator and generator • Advantages
  • 3. Iterators • An iterator is an object which allows a programmer to traverse through all the elements of a collection, regardless of its specific implementation. • An iterator is an object which implements the iterator protocol. • The iterator protocol consists of two methods: • The __iter__() method which must return the iterator object and next() method which returns the next element of sequence.
  • 4. Examples We use for statement for looping over a list. >>> for i in [1, 2, 3, 4]: ... print i, ... 1 2 3 4
  • 5. Examples If we use it with a string, it loops over its characters. >>> for c in "python": ... print c ... p y t h o n
  • 6. Examples If we use it with a dictionary, it loops over its keys. >>> for k in {"x": 1, "y": 2}: ... print k ... y x
  • 7. Examples If we use it with a file, it loops over lines of the file. >>> for line in open("a.txt"): ... print line, ... first line second line
  • 8. Iteration protocol • The built-in function iter takes an iterable object and returns an iterator. • Each time we call the next method on the iterator gives us the next element. • If there are no more elements, it raises a StopIteration.
  • 9. Examples >>> x = iter([1, 2, 3]) >>> x <listiterator object at 0x1004ca850> >>> x.next() 1 >>> x.next() 2 >>> x.next() 3 >>> x.next() Traceback (most recent call last): File <stdin>, line 1, in <module> StopIteration
  • 10. Examples class yrange: def __init__(self, n): self.i = 0 self.n = n def __iter__(self): return self def next(self): if self.i < self.n: i = self.i self.i += 1 return i else: raise StopIteration() Iterators are implemented as classes. Here is an iterator that works like built- in xrange function.
  • 11. Examples • The __iter__ method is what makes an object iterable. • Behind the scenes, the iter function calls __iter__ method on the given object. • The return value of __iter__ is an iterator. • It should have a next method and raise StopIteration when there are no more elements.
  • 12. Examples >>> y = yrange(3) >>> y.next() 0 >>> y.next() 1 >>> y.next() 2 >>> y.next() Traceback (most recent call last): File <stdin>, line 1, in <module> File <stdin>, line 14, in next StopIteration
  • 13. Infinite Iterators • It is not necessary that the item in an iterator object has to exhaust. • There can be infinite iterators (which never ends). • We must be careful when handling such iterator.
  • 14. Examples >>> a = iter(InfIter()) >>> next(a) 1 >>> next(a) 3 >>> next(a) 5 >>> next(a) 7 class InfIter: """Infinite iterator to return all odd numbers""" def __iter__(self): self.num = 1 return self def __next__(self): num = self.num self.num += 2 return num
  • 15. Generators • Generators simplifies creation of iterators. • A generator is a function that produces a sequence of results instead of a single value. • A generator is a special routine that can be used to control the iteration behaviour of a loop. • A generator is similar to a function returning an array. • A generator has parameters, it can be called and it generates a sequence of result. • But unlike functions, which return a whole array, a generator yields one value at a time.
  • 16. Generators Generators in Python: • Are defined with the def keyword • Use the yield keyword • May use several yield keywords • Return an iterator
  • 17. Examples def yrange(n): i = 0 while i < n: yield i i += 1 Each time the yield statement is executed the function generates a new value.
  • 18. Examples >>> y = yrange(3) >>> y <generator object yrange at 0x401f30> >>> y.next() 0 >>> y.next() 1 >>> y.next() 2 >>> y.next() Traceback (most recent call last): File <stdin>, line 1, in <module> StopIteration
  • 19. Examples • A generator is also an iterator. • The word “generator” is confusingly used to mean both the function that generates and what it generates. • When a generator function is called, it returns a generator object without even beginning execution of the function. • When next method is called for the first time, the function starts executing until it reaches yield statement. • The yielded value is returned by the next call.
  • 20. Examples >>> def foo(): ... print "begin" ... for i in range(3): ... print "before yield", i ... yield i ... print "after yield", i ... print "end" ... >>> f = foo() >>> f.next() begin before yield 0 0 >>> f.next() after yield 0 before yield 1 1 >>> f.next() after yield 1 before yield 2 2 >>> f.next() after yield 2 end Traceback (most recent call last): File <stdin>, line 1, in <module> StopIteration >>>
  • 21. Examples • Lets say we want to write a program that takes a list of filenames as arguments and prints contents of all those files. • The traditional way to implement it is: def cat(filenames): for f in filenames: for line in open(f): print line,
  • 22. Examples • Now, lets say we want to print only the line which has a particular substring. def grep(pattern, filenames): for f in filenames: for line in open(f): if pattern in line: print line, • Both these programs have lot of code in common. It is hard to move the common part to a function. But with generators makes it possible to do it.
  • 23. Examples def readfiles(filenames): for f in filenames: for line in open(f): yield line def grep(pattern, lines): return (line for line in lines if pattern in line) def printlines(lines): for line in lines: print line, def main(pattern, filenames): lines = readfiles(filenames) lines = grep(pattern, lines) printlines(lines)
  • 24. Generator expressions • There are two types of generators in Python: generator functions and generator expressions. • A generator function is any function in which the keyword yield appears in its body. • The appearance of the keyword yield is enough to make the function a generator function. • The other type of generators are the generator equivalent of a list comprehension. Its syntax is really elegant for a limited use case.
  • 25. Examples >>> numbers = [1, 2, 3, 4, 5, 6] >>> [x * x for x in numbers] [1, 4, 9, 16, 25, 36] You could do the same thing with a set comprehension: >>> {x * x for x in numbers} {1, 4, 36, 9, 16, 25} Or a dict comprehension: >>> {x: x * x for x in numbers} {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}
  • 27. Advantages • Cleaner code • Iterators can work with infinite sequences • Iterators save resources • Generator allows to write streaming code with fewer intermediate variables and data structures. • Memory and CPU efficient