0% found this document useful (0 votes)
33 views5 pages

Generators

Generators in pytrhon detail explanation
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views5 pages

Generators

Generators in pytrhon detail explanation
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
You are on page 1/ 5

Generators in python (Generator Functions)

-> Generator is a special type of function which is responsible to


generate a sequence of values.
-> We can write generator functions just like ordinary functions,
but it uses a special keyword ‘yield’ to return values.

Collections vs Generators
->

Write a generator function to generate 3 values ‘A’, ‘B’, ‘C’?


-> def mygen():
yield ‘A’
yield ‘B’
yield ‘C’

-> If we reach the end then we will get RuntimeException


StopIteration.

Write a generator function to generate first n values?


->

Write a generator function to generate values for countdown with


provided max value?
->

Collections vs Generators
->

Advantages and limitation of generator?


-> Performance will be improved when compared with traditional
collections.
-> Memory utilization will be improved when compared with
traditional collections.
-> Best suitable if we want to handle very huge amount of data
like handling data from lakhs of files, handling lakhs of records
from database etc.

Limitation
-> it won’t store data.
-> We cannot ask a particular element.

How to convert generator object into the list?


-> By using list function we can convert generator object into list.

Generators deep dive


-> Generators is a type of iterator
-> Generators function is a generator factories, they return a
generator when called, they are not a generator themselves.
-> Generator expression, uses the comprehension syntax, a more
concise way of creating generators, like list comprehensions,
useful for simple situations.
-> Performs consideration generators vs list comprehension.

Yielding and Generator functions


-> What if we could do something like this instead.

Def factorial(n):
for i in range(n):
emit factorial(i)
pause execution here
wait for resume
return ‘done!’
And in our code we want to do something like this maybe
-> facts = factorials(4)
-> We create an instance of factorials, so calling an function does
not do an iteration, it just create an some object.
-> and maybe we call something like give the next factorial.
get_next(0)!
get_next(1)!

-> of course getting 0!, 1!, 2! followed by a string is odd.


-> and what happens if we call get_next again.
-> maybe we should consider raising an exception.. StopIteration?
-> And instead of calling get_next, why not just use next?
-> But what about that emit, pause and resume? => yield

yield to the rescue


-> The yield keyword does exactly what we want
a) it emits a value
b) the function is effectively suspended (but it retains its current
state) so all its stack frame, all its local scope, all its values is there
it retains that.
c) calling next on the function resumes running the function right
after the yield statement.

-> if function returns something instead of yielding finishes


running-> StopIteration exception.

Def song():
print(‘line 1’)
yield “I am a lumberjack and I’m ok”
print(‘line 2’)
yield “I sleep all night and I work all day”

-> When we call generator function python saw that there is a


yield keyword, inside this function, it does not run the body of the
function.
Lines = song()
-> We can call next on the function instance
line = next(lines)
-> ‘line 1’ is printed in console.
-> line -> “I’m a lumberjack and I’m OK”

-> A function that uses the yield statement, is called a generator


function.
-> Is just a regular function but uses yield keyword and returns a
generator.
-> The generator is created by python when the function is called.
-> The generator internally implement the iterator protocol.
-> The resulting generator is executed by calling next(), it starts
executing the body of function until it hit the yield keyword.
-> it yield the value (as return value of next()) then it suspends
itself.
-> until next is called again -> suspended function resumes
execution.

-> if it encounters a return before a yield: then we will get a


StopIteration exception occurs.

-> in fact, generators are iterators, they implement the iterator


protocol. __iter__, __next__

-> They are exhausted when function returns a value, StopIteration


exception, return value is the exception message.

-> gen.__iter__() or iter(gen) -> returns generator itself.

Def factorials(n)
for i in range(n):
yield math.factorial(i)

fact_iter = factorials(5)
Generator functions which contain atleast one yield statement.

When a generator function is called, Python creates a generator


object.

Generators implement the iterator protocol.

Generators are inherently lazy iterators (and can be infinite)

Generators are iterators, and can be used in the same way (for
loops, comprehensions) etc.

You might also like