What's «yield» in python made for? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What's «yield» in python made for?

Hi, I'm wondering about the use of «yield», besides of returning a sequence of data, what's the main thing that it's made for ? Thank you.

15th Apr 2018, 6:29 AM
Maze Runner
Maze Runner - avatar
3 Answers
+ 5
To understand what yield does, you must understand what generatorsare. And before generators come iterables. Iterables When you create a list, you can read its items one by one. Reading its items one by one is called iteration: Generators Generators are iterators, a kind of iterable you can only iterate over once. Generators do not store all the values in memory, they generate the values on the fly: >>> mygenerator = (x*x for x in range(3)) >>> for i in mygenerator: ... print(i) 0 1 4 It is just the same except you used () instead of []. BUT, you cannotperform for i in mygenerator a second time since generators can only be used once: they calculate 0, then forget about it and calculate 1, and end calculating 4, one by one. Yield yield is a keyword that is used like return, except the function will return a generator. >>> def createGenerator(): ... mylist = range(3) ... for i in mylist: ... yield i*i ... >>> mygenerator = createGenerator() # create a generator >>> print(mygenerator) # mygenerator is an object! <generator object createGenerator at 0xb7555c34> >>> for i in mygenerator: ... print(i) 0 1 4 Here it's a useless example, but it's handy when you know your function will return a huge set of values that you will only need to read once. To master yield, you must understand that when you call the function, the code you have written in the function body does not run.The function only returns the generator object, this is a bit tricky :-) Then, your code will be run each time the for uses the generator. Details: https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do
15th Apr 2018, 6:38 AM
📈SmileGoodHope📈
📈SmileGoodHope📈 - avatar
+ 1
Thank you brother.
15th Apr 2018, 7:26 AM
Maze Runner
Maze Runner - avatar
+ 1
Maze Runner you are welcome
15th Apr 2018, 7:28 AM
📈SmileGoodHope📈
📈SmileGoodHope📈 - avatar