0

What is the use of "yield" keyword in python

18th May 2020, 10:11 AM
Teja Swaroop
Teja Swaroop - avatar
4 Respuestas
+ 5
Piduguralla Naga Sai Mani Teja Swaroop When you define a function, you have 3 options that I know of. print - will create an output each time the function is called. return - will create a result, but will stop any further iteration, therefore stopping any further results from being generated. Yield - will allow further results being generated if those results are available.
18th May 2020, 10:24 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 5
Here is a sample code, that demonstrates the use of yield. Variable "c" will hold a generator object after count_to_5() is called. This can now be iterated by a for loop. There is a permanent connection between the function call and the function itself. This is only possible when yield is used. Keep in mind that the generator object hold in "c" can only be iterated once. If you try to retrieve the values again, you will get an empty []. def count_to_5(): for i in range(1,6): yield (i) c = count_to_5() for i in c: print(i) # instead of last three lines, it is also possible to use: for i in count_to_5(): print(i) # or you can use a comprehension: [print(i) for i in count_to_5()]
18th May 2020, 10:41 AM
Lothar
Lothar - avatar
+ 2
https://www.geeksforgeeks.org/JUMP_LINK__&&__python__&&__JUMP_LINK-yield-keyword/amp/ Have a look hay Anjali Raj instead of copying from Google try to give direct link . ok
18th May 2020, 10:14 AM
Ayush Kumar
Ayush Kumar - avatar