SlideShare a Scribd company logo
Advance Python
What are Generators ?
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

More Related Content

PPTX
Iterarators and generators in python
PPTX
python ppt.pptx
PPTX
08-Iterators-and-Generators.pptx
PDF
Python Generators
PDF
Python lecture 12
PPTX
Python advance
PDF
Generators: The Final Frontier
Iterarators and generators in python
python ppt.pptx
08-Iterators-and-Generators.pptx
Python Generators
Python lecture 12
Python advance
Generators: The Final Frontier

Similar to Generators-in-Python-for-Developers.pptx (20)

PDF
Generators in Python.pdf
PPTX
Python Programming Essentials - M35 - Iterators & Generators
PDF
Python master class 2
PPTX
Generators In Python
PDF
Python iteration
PDF
Generators
PPTX
Advance-Python-Iterators-for-developers.pptx
DOCX
Generator iterator methods
PDF
A tour of Python
PDF
An overview of Python 2.7
PPT
Python Programming Introduction - Loops & Boolean
PPTX
14-Python-Concepts for data science.pptx
PPTX
Pa1 session 2
PDF
The Vanishing Pattern: from iterators to generators in Python
PDF
Intro to Python
PDF
PythonStudyMaterialSTudyMaterial.pdf
PDF
Introduction-to-Iteration.pdf
PDF
Generator Tricks for Systems Programmers, v2.0
PDF
Python Generator Hacking
PPTX
Chapter 2-Python and control flow statement.pptx
Generators in Python.pdf
Python Programming Essentials - M35 - Iterators & Generators
Python master class 2
Generators In Python
Python iteration
Generators
Advance-Python-Iterators-for-developers.pptx
Generator iterator methods
A tour of Python
An overview of Python 2.7
Python Programming Introduction - Loops & Boolean
14-Python-Concepts for data science.pptx
Pa1 session 2
The Vanishing Pattern: from iterators to generators in Python
Intro to Python
PythonStudyMaterialSTudyMaterial.pdf
Introduction-to-Iteration.pdf
Generator Tricks for Systems Programmers, v2.0
Python Generator Hacking
Chapter 2-Python and control flow statement.pptx
Ad

More from Ganesh Bhosale (20)

DOCX
3.AWR and ASH Reportsfor Oracle Tuning.docx
DOCX
Step by stepDoc for Oracle TuningsandAWR.docx
PPTX
2.Python_Testing_Using_PyUnit_PyTest.pptx
PPTX
1.Python_Testing_Using_PyUnit_Pytest.pptx
PPTX
2.Python_Unit _Testing_Using_PyUnit_Pytest.pptx
PPTX
awsfundamentals1_cloud_Infrastructure.pptx
PPTX
The ES Library for JavaScript Developers
PPTX
Git Repository for Developers working in Various Locations
PPTX
4.Problem Solving Techniques and Data Structures.pptx
PPTX
3.Problem Solving Techniques and Data Structures.pptx
PPTX
2.Problem Solving Techniques and Data Structures.pptx
PPTX
1. Problem Solving Techniques and Data Structures.pptx
PPTX
unittestinginpythonfor-PYDevelopers.pptx
PPTX
SQL-queries-for-Data-Analysts-Updated.pptx
PPTX
javascriptbasicsPresentationsforDevelopers
PPTX
Cloud-Architecture-Technology-Deovps-Eng
PDF
Backup-and-Recovery Procedures decribed in AWS
PPTX
KMSUnix and Linux.pptx
PPT
RDBMS_Concept.ppt
PPTX
CLI.pptx
3.AWR and ASH Reportsfor Oracle Tuning.docx
Step by stepDoc for Oracle TuningsandAWR.docx
2.Python_Testing_Using_PyUnit_PyTest.pptx
1.Python_Testing_Using_PyUnit_Pytest.pptx
2.Python_Unit _Testing_Using_PyUnit_Pytest.pptx
awsfundamentals1_cloud_Infrastructure.pptx
The ES Library for JavaScript Developers
Git Repository for Developers working in Various Locations
4.Problem Solving Techniques and Data Structures.pptx
3.Problem Solving Techniques and Data Structures.pptx
2.Problem Solving Techniques and Data Structures.pptx
1. Problem Solving Techniques and Data Structures.pptx
unittestinginpythonfor-PYDevelopers.pptx
SQL-queries-for-Data-Analysts-Updated.pptx
javascriptbasicsPresentationsforDevelopers
Cloud-Architecture-Technology-Deovps-Eng
Backup-and-Recovery Procedures decribed in AWS
KMSUnix and Linux.pptx
RDBMS_Concept.ppt
CLI.pptx
Ad

Recently uploaded (20)

PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PPTX
TLE Review Electricity (Electricity).pptx
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
1. Introduction to Computer Programming.pptx
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
cloud_computing_Infrastucture_as_cloud_p
PDF
Mushroom cultivation and it's methods.pdf
PDF
Getting Started with Data Integration: FME Form 101
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Encapsulation theory and applications.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Univ-Connecticut-ChatGPT-Presentaion.pdf
PDF
August Patch Tuesday
PPTX
A Presentation on Artificial Intelligence
Assigned Numbers - 2025 - Bluetooth® Document
Accuracy of neural networks in brain wave diagnosis of schizophrenia
gpt5_lecture_notes_comprehensive_20250812015547.pdf
TLE Review Electricity (Electricity).pptx
Group 1 Presentation -Planning and Decision Making .pptx
Encapsulation_ Review paper, used for researhc scholars
1. Introduction to Computer Programming.pptx
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
SOPHOS-XG Firewall Administrator PPT.pptx
Building Integrated photovoltaic BIPV_UPV.pdf
Programs and apps: productivity, graphics, security and other tools
cloud_computing_Infrastucture_as_cloud_p
Mushroom cultivation and it's methods.pdf
Getting Started with Data Integration: FME Form 101
Mobile App Security Testing_ A Comprehensive Guide.pdf
Encapsulation theory and applications.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
Univ-Connecticut-ChatGPT-Presentaion.pdf
August Patch Tuesday
A Presentation on Artificial Intelligence

Generators-in-Python-for-Developers.pptx

  • 1. Advance Python What are Generators ?
  • 2. 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.
  • 3. Generators Generators in Python: • Are defined with the def keyword • Use the yield keyword • May use several yield keywords • Return an iterator
  • 4. 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.
  • 5. 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
  • 6. 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.
  • 7. 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 >>>
  • 8. 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,
  • 9. 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.
  • 10. 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)
  • 11. 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.
  • 12. 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}
  • 14. 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