r/shittyprogramming • u/CVh655FDBcZ1l • Apr 10 '19
One Line of Code™
https://gist.github.com/WorryingWonton/ce8a3a74b0298f0b734fe4dd0a883a63
101
Upvotes
r/shittyprogramming • u/CVh655FDBcZ1l • Apr 10 '19
View all comments
Show parent comment
1
u/Athandreyal Apr 11 '19
Definitely deeper than I am comfortable of my knowledge in the subject. I understand their differences for the most part, but not very well versed in what those differences mean in practice.
I actually hadn't realised generator expressions were a thing for a start, so my choice of [] was one of not realising there were an alternative.... I knew of generator functions, just not the expressions.
Still, having read up a little, filling in some things I didn't know, I think I can provide some answer, though I too would welcome someone more versed than i weighing in, should anyone happen by....
Python doesn't do lazy eval, but generators can fake it by delaying the work until its demanded of them. They also only provide one element at a time (and do not keep the previous elements) versus the complete set. This means generators will obliterate other expressions for memory footprint. It also means they can handle effectively infinite sets, because they don't need to produce the whole set, just another element everytime they are asked. Note that infinite productions are still quite plausible if the loop doesn't stop asking for values expecting it to end instead.
Performance is nearly identical either way, since the means of generating the next element is often the same, or a bit less efficient, than just producing the complete set in one go.
Iterators stand inbetween with being completely evaluated on execution, but implementing generator like syntax such as .next().
So list comprehension, or generator expression, sum was going to receive the same number of values, and both expressions were going to do essentially all the same work. But we don't actually need the list after the fact, and sum doesn't care if the values arrive all at once or one by one through a generator. Generator wins I would think.
For the task above, either is suitable. Sure the generators are smaller, but neither presents a notable demand for memory.
All that said, I think you are correct in having expected the generator expression. If you need the list, go for the comprehension. I didn't need the list though, just the result of having sum do work on it, so a generator it should have been.