GENERATORS
Generators are almost like Iterators, but can only
iterate once over them. It is because they do not store all the values in
memory, they generate the values on the fly.
Either generators are used with a for loop or bypassing them to any function or construct that
iterates., mostly they are implemented as functions.
Before proceeding further, you should know that
generators do not return a value,
they yield.
Let’s look at the example below,
Well it is not useful here in this case, but
generators are best for calculating large sets of results, particularly calculations
involving loops themselves, where you don’t want to allocate the memory for all
the results at the same time.
Note:- Many Standard Library functions that return lists in Python 2 have been modified to
return generators in Python 3
because generators require fewer
resources.
Below is an example, generator which calculates Fibonacci numbers,
This way we don’t have to worry about it using a lot
of resources, but if we implemented it like this,
Def fibo(n):
a = b = 1
result=[]
for i in range(n):
result.append(a)
a, b = b, a+b
return result
it would have used up all our resources while
calculating a large input.
We have discussed that generators can only once iterate but we haven’t actually tested it,
but before proceeding to the testing part, we need to know about next() built-in function. It allows us
to access the next element of a sequence.
Lets test out our understanding,
As we can see that after yielding all the values next() caused a StopIteration error. Basically, this error informs us that all the values have been yielded. You might be wondering why we don’t get this error when using for loop. Well, the answer is simple. The for loop automatically catches this error and stops calling next.
Hello Python people, for this blog we have taken help from the book Python : The Complete Reference.
If you still have any doubt on this topic then do come to us via email "sophomoretechs@gmail.com" or via Instagram "@coding.winds".
Do subscribe to our daily blog update by clicking here.
Thank You!
No comments:
Post a Comment