Sololearn: Learn to Code
New course! Every coder should learn Generative AI!
Try a free lesson
+ 6
To add to Gordie's answer: Let's say you want to find the first 1 million prime numbers. If you write a regular function, you call the function once and it will block the control flow of your program until it has done its job and found one million prime numbers (which might take a couple of minutes, probably leaving your program unresponsive in that time). Then it will return a huge list of one million numbers that you'll have to process somehow. Maybe your program will run out of space after it already generated 800,000 prime numbers and all of your progress will be lost because your program crashed before your function could return anything. A generator function will generate one prime number at a time and only generate one more number if you explicitly tell it to (usually by calling next()). So you basically create an instance of the generator function once and then keep calling the next result of that generator object a million times in order to get one million numbers. The control flow will constantly jump back and forth between your main program and the generator function. While the generator keeps creating more and more numbers, you can process them in the background simultaneously (especially if you use several threads). So you can take control of your generator function, use/examine the output as it is generated and only generate as much output as you need without the risk that your unresponsive program already died minutes/hours ago without you even noticing.
20th Jun 2019, 10:45 AM
Anna
Anna - avatar