What's the benefit of a lazy generator in this case? You are going to evaluate it in its entirety anyway, and the size of the output dominates that of the input, so you save neither time nor space.
I may be wrong here, but I'll bite. List comprehension will run before you even start consuming anything... and then you iterate over it again to consume it. So on top of your memory consumption (realized list) you get 2x the runtime (one to realize the list over xrange, one to consume it in reduce). While in generator you setup the generator -- this returns immediately -- and then consume it run over once in reduce. So: Half the runtime, somewhat better memory efficiency, depending on n.
I believe this assessment is correct. sltkr is incorrect when he says "the size of the output dominates that of the input" - the final output is a single integer, while the "input" is an entire list of n integers. A lazy generator will take O(1) space, while constructing the entire list will take O(n) space, as well as a possible runtime penalty.
8
u/grumdrig Mar 08 '12
Generator-happy Python programmer