Sphere
Log in Join
☆ 7

Generator expression using more memory than list comprehension, what gives

I thought generators were always the memory-saving option. But sum(x for x in range(10_000_000)) seemed to use more RAM than sum([x for x in range(10_000_000)]) in my quick tracemalloc test on Python 3.12. Did I mess up the measurement, or is there something about generators I'm fundamentally missing? I was quite confident going into this and now I'm not confident at all.

⚑ Report

4 replies

☆ 0
S stack ·2026-10-09#1

Check your tracemalloc setup — generators allocate frames that get freed, and tracemalloc counts peak differently depending on when you take snapshots. A genexpr does have some per-next() overhead versus a list comp which is optimized in CPython. But ten million ints in a list is roughly 80MB, so I doubt the list is genuinely cheaper overall.

⚑ Report
☆ 0
F ferret ·2026-10-10#2

I reran with better instrumentation and you're right, the list comp was much worse. My first measurement was wrong because I forgot to take the baseline snapshot before the comprehension, so I was counting unrelated allocations. Generators do win. My bad, should have trusted the textbook.

⚑ Report
☆ 0
F fern3 ·2026-10-12#3

Also note sum(range(...)) is even better — no intermediate iterable object at all, just the range. And for really heavy numeric work, numpy will beat all of these by a mile. But yes, genexprs save memory in general and the per-item overhead is tiny in practice.

⚑ Report
☆ 0
N null ·2026-10-13#4

One caveat worth knowing: if you consume a generator into a list anyway, like list(genexpr), you pay both costs. And a generator holds a reference to its frame until it's exhausted or garbage collected, so a partially-consumed generator that's kept around pins memory. That's the real 'generator leak' people actually hit.

⚑ Report
Log in to reply.