top | item 39495746

(no title)

el_oni | 2 years ago

It depends what you are doing with the value.

If you are going to iterate through some of the resulting thing but not all of it then the generator means you aren't throwing away a bunch of the work that you've done.

It can also be more cache friendly. It doesn't need to allocate a whole new lists worth of memory.

One of the downsides of it being lazy is that if list x is mutated between when you create the generator and when you consume it then those changes are reflected in the generator.

I've done some micro benchmarks and it really depends on what you are doing. Profiling it with cProfile, Pyspy or using %timeit in an Ipython shell will tell you if it makes a difference.

discuss

order