A MemoryError occurs when a Python program tries to use more memory than the system can provide. This usually happens when very large objects are created, memory usage grows continuously inside loops, or recursive functions consume excessive memory.
data = [0] * (10**10)
Output
MemoryError
Explanation: [0] * (10**10) attempts to create a list containing billions of elements. This requires a huge amount of memory, which may exceed the available system memory and result in a MemoryError.
Common Causes of MemoryError
1. Infinite Loop Creating Data: Continuously adding data inside an infinite loop causes memory usage to grow without limit.
items = []
while True:
items.append("data")
Output
MemoryError
Explanation: list items keeps growing because new elements are continuously added. Eventually, all available memory is consumed, causing a MemoryError.
2. Creating Very Large Data Structures: Allocating extremely large lists, strings or dictionaries can exceed available memory.
text = "a" * (10**9)
print(len(text))
Output
MemoryError
Explanation: expression "a" * (10**9) attempts to create a string containing one billion characters, which may require more memory than the system can provide.
3. Recursive Function Without a Base Case: A recursive function that never stops keeps creating new function calls and consumes memory continuously.
def count(n):
return count(n + 1)
count(1)
Output
RecursionError: maximum recursion depth exceeded
Explanation: function keeps calling itself indefinitely because it has no stopping condition. Although Python typically raises a RecursionError first, excessive recursion is a common cause of memory-related issues.
Handling MemoryError
1. Limit Data Growth: Avoid creating infinitely growing data structures by limiting the amount of stored data.
items = []
for _ in range(1000):
items.append("data")
print(len(items))
Output
1000
Explanation: loop runs only 1000 times, so memory usage remains controlled and predictable.
2. Process Data in Smaller Chunks: Instead of loading everything into memory at once, process data in smaller portions.
for i in range(5):
chunk = [0] * 1000
print(len(chunk))
Output
1000 1000 1000 1000 1000
Explanation: Only a small chunk of data is created during each iteration, reducing overall memory consumption.
3. Add a Base Case in Recursive Functions: Always include a termination condition when using recursion.
def count(n):
if n == 5:
return
print(n)
count(n + 1)
count(1)
Output
1 2 3 4
Explanation: condition if n == 5 stops the recursion, preventing excessive memory usage and stack growth.
4. Using try-except: A try-except block can be used to handle MemoryError gracefully.
try:
data = [0] * (10**10)
except MemoryError:
print("Not enough memory available.")
Output
Not enough memory available.
Explanation: If Python cannot allocate enough memory, the MemoryError is caught and a custom message is displayed instead of abruptly terminating the program.