Generator vs list memory

EasyIterator & Generator Programs · 17 of 20

Write a Python program that compares the memory of a list and a generator of a million numbers.

Advertisement
Output
True True

Approach

  1. sys.getsizeof.

Solution

Python
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.

More iterator & generator programs

← All 20 Iterator & Generator Programs

Leave a Comment