+ 2
Why use generators
I get that generators are a thing but why should I bother learning this new syntax when for/while loops work just as well?
2 odpowiedzi
+ 9
dav Generators are different than for/while loops. I'm not sure what you mean by they are "a thing" or "new syntax".
Think of a generator as being similar to an array or list rather than as a loop. Generators are used in a loop, just as an array or list might be.
The biggest difference between a generator and something like an array or list is the values in the generator aren't explicitly stored in memory, they are computed.
I like this article as it focuses on how to think about usages for generators as a programmer.
NOTE: This article can apply to generators in all languages, not just Python.
https://www.oreilly.com/ideas/2-great-benefits-of-python-generators-and-how-they-changed-me-forever