sum(x * x for x in range(10**8)) versus sum([x * x for x in range(10**8)]). What is the key difference?
Options
- The generator version is always faster because it skips the loop
- The generator version holds one item at a time, so memory stays flat (Correct option)
- Both versions are identical after Python compiles them to bytecode
- The list version is lazy and only builds values when sum asks
Answer
The generator version uses roughly constant memory; the list version builds 100M items first
Why
With square brackets [...] Python first builds a complete list of 100 million numbers in memory, and only then sum adds them.
With parentheses (...) it is a generator expression: each number is created only when sum asks for the next one, so only one number exists at a time.
Same result, far less memory.
Remember
Use generators for big data you only loop over once.