In python, what is the difference between MemoryError and OverflowError?

memory, out-of-memory, python

Solution

In the first example, you try to pass a list of 1,000,000,000 integers to the generator expression. You computer runs out of memory trying to create that list. In Python 3, I suspect this would work, since `range` itself produces a generator instead of an explicit list.

In the second example, I suspect `range` requires a 32-bit value for its input on your machine, and so throws a different error before it can run out of memory.

Problem

It seems that both exceptions are raised in similar situation. What is the difference and what happens behind the scenes in each of these two code lines? ``` >>> (i for i in range(1000000000)) # 10^9 Traceback (most recent call last): File "<stdin>", line 1, in <module> MemoryError >>> (i for i in range(10000000000)) # 10^10 Traceback (most recent call last): File "<stdin>", line 1, in <module> OverflowError: range() result has too many items ```

Original source