← Python lessons

Python Generator Expression vs List: Memory (getsizeof)

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

A generator expression vs a list in Python is a choice about memory. A list stores every value. A generator expression stores only how to make the next one. sys.getsizeof() shows the difference in bytes.

You will measure both, and see what a generator gives up in return. Prerequisites: Python Generator Expressions Explained.

Measure memory with sys.getsizeof()

sys.getsizeof(thing) returns the size of an object in bytes.

import sysas_list = [number * 2 for number in range(1000)]as_generator = (number * 2 for number in range(1000))print(sys.getsizeof(as_list))print(sys.getsizeof(as_generator))

On one 64-bit computer this printed 8856 and 208. Your numbers will differ: they depend on the Python version and the machine, and a browser gives smaller ones. The gap is what matters.

A generator stays the same size

A list grows with its contents. A generator does not, because it holds no values.

import syssmall = (number for number in range(10))huge = (number for number in range(10_000_000))print(sys.getsizeof(small) == sys.getsizeof(huge))short_list = [number for number in range(10)]long_list = [number for number in range(10_000)]print(sys.getsizeof(short_list) < sys.getsizeof(long_list))

Both lines print True. Comparisons like these give the same answer on every machine, unlike raw byte counts.

Get the same answer from sum()

sum(), max(), min() and any() read values one at a time. They do not need a list.

as_list = [number * 2 for number in range(1000)]as_generator = (number * 2 for number in range(1000))print(sum(as_list))print(sum(as_generator))

Both print 999000. The generator made each value, added it, and let it go.

What a generator gives up

A generator can be read once. It has no length and no index.

as_generator = (number * 2 for number in range(1000))print(sum(as_generator))print(sum(as_generator))print(len(as_generator))  # this line raises TypeError: a generator has no len()

This prints 999000, then 0, then stops with the error. The second sum() found the generator already used up.

Choose a list when you need len(), an index, sorting or a second pass. Choose a generator expression when the values are read once and there are many of them.

Note: sys.getsizeof() measures only the list itself: one slot per item. The numbers stored in those slots take extra memory, so a real list costs more than the figure shown.

See also: List comprehensions, Python yield vs return.

Your turn

Create evens, a generator expression of the even numbers below 1000. Print whether it is under 500 bytes, then print its sum.

🎯 Goal — make it print exactly:
True
249500
import sys# add three lines: create evens, print sys.getsizeof(evens) < 500, then print sum(evens)