Why Generater in python is memory-efficient? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why Generater in python is memory-efficient?

Does it only store the state of the function required to yield value next time. Does it store only currently yielded result but not previous result? (This way it going to save memory as generator is one time operation, correct me if I'm wrong) If it only store currently executed result, thus it will compute everything again from beginning to yield next result? please explain me thank you.

12th Sep 2021, 2:42 PM
I Am a Baked Potato
I Am a Baked Potato - avatar
5 Answers
+ 1
While a very long [list] alocate alot of memory. It will cause memory error. & genarator iterate thus alocating less memory.
12th Sep 2021, 3:51 PM
Iftekhar Ahmed Pranto
Iftekhar Ahmed Pranto - avatar
+ 1
Yes. A big dataset returns the full dataset thus using more memory. You can think of generators as returning multiple items, as if they return a list, but instead of returning them all at once they return them one-by-one, and the generator function is paused until the next item is requested.
12th Sep 2021, 4:39 PM
Iftekhar Ahmed Pranto
Iftekhar Ahmed Pranto - avatar
+ 1
Pranto Thank you! Also as it is not storing previous result does it going to compute from beginning again to yield next value?
12th Sep 2021, 5:07 PM
I Am a Baked Potato
I Am a Baked Potato - avatar
+ 1
No it wont start over. Pause yeield and start again
12th Sep 2021, 7:31 PM
Iftekhar Ahmed Pranto
Iftekhar Ahmed Pranto - avatar
0
Pranto Yes we iterating as generator return iterator, but I'm asking reason why it take less memory does it only store currently yielded value in memory when we demand for it?
12th Sep 2021, 4:01 PM
I Am a Baked Potato
I Am a Baked Potato - avatar