Answer the question
In order to leave comments, you need to log in
How long to use generators?
Hello.
I am now at the stage of loving generators that I use them a lot more than lists. Literally everywhere, I use only yield and yield from
Lists only if you need to iterate over the sequence once, and then again. Or if you need to send a list via API and make JSON out of it. That is, even if the iteration is near-parallel, for example, with a lag of a couple of elements, I use itertools.tee
I know that generators are slower than lists (although I could not think of adequate benchmarks, because generators are lazy and how to test exactly the time, spent on yield is not clear). Although, creating a list with appends plus processing it usually takes longer:
I know that almost all lists that I would create instead of generators would whiz into memory, but I can't stop saving this memory.
Can you give me advice on when it is appropriate to use generators, and when it is stupid?
Answer the question
In order to leave comments, you need to log in
Ek you, brother, hooks))) You might think that the only purpose of lists is to iterate over them)
But we know that everything is just the opposite: generators are for iteration, and lists are for random access (well, to iterate ).
Generators not only save memory, but also consume it - per persistent stack frame, at least. So there is no point in saving on small lists.
And vice versa - generators can win in speed where the calculation of values is difficult, and the iteration can break without filling the list / generator to the end.
https://stackoverflow.com/questions/47789/generato... it 's written here
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question