yield keyword in Python
This tutorial will give us about the use of yield keyword in Python.
About the yield keyword in Python:
- The yield keyword is like a return keyword using to avoid the more space covered by the data.
- And it is using to reduce the time complexity for executing the code rather than using the return keyword in functions.
Here we are going to know how it will work in Python:
def fun(n): for i in range(0,n): yield i s=int(input()) a=fun(s) print(a) for i in a: print(i)
5 <generator object fun at 0x00000251BB471EB0> 0 1 2 3 4
Description: From the above example we observing that we took a function as fun() and we passed some integer value by creating a generator as ‘a’ for the fun() function.
“Because of using this generator we avoid the data structures for storing the sequential data that is it can store the sequential data,
Here generator is nothing but the object for the function.”
When we pass the ‘s’ value to the function it iterates ‘s’ time and stores the value given by the yield each time into the generator ‘a’ sequentially.
When we print the ‘a’ value the output came as <generator object fun at 0x00000251BB471EB0> because ‘a’ is a generator,
Because that is not a data structure.
Finally when we gave the ‘for’ loop at the end for printing the values which are present in the generator,
And we got the output as 0,1,2,3,4 up to ‘s’ values
We have to know what can be done if we use ‘return’ keyword in place of yield:
If we want to get the output like the above program using the return keyword we should use the data structures for storing the data.
And if we use the data structure it will take more iterations and more time when compared to the above example,
Here we can see that program…
def fun(n): l= for i in range(0,n): l.append(i) return l k=fun(5) print(k)
Output: [0, 1, 2, 3, 4]
Description: From the above example we got the output as a list because we return the list from the function.
This is helpful for small data storing with small iterations.
If we want to store the large data lists will take more space and goes to a waste of time taken for execution,
So we can use the yield keyword to avoid these problems
If you want to know about exec and eval functions in Python you can see here About eval and exec functions in Python