8 ms·
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 ar
by el_oni 3y 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.
- el_oni 3y agoP.s. to make that function an actual generator you could use yield from Instead of return
- keeganpoppen 3y agothe function isn't a generator, but that value is a generator expression: https://peps.python.org/pep-0289/ https://peps.python.org/pep-0289/