Python Practice › Iterator & Generator Programs › Program 17
Generator vs list memory
Write a Python program that compares the memory of a list and a generator of a million numbers.
Output
True True
Approach
sys.getsizeof.
Solution
import sys as_list = [n for n in range(1_000_000)]as_gen = (n for n in range(1_000_000))print(sys.getsizeof(as_list) > 1_000_000, sys.getsizeof(as_gen) < 1_000)Output
True True
Note
The exact byte counts depend on the Python version, so the program prints comparisons.
Learn the concept
New to this topic? Read the lesson, then come back.