Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python MemoryError when appending a list

I've a small Python (2.7.10) script, which you can see below.

def numbers_calc(max_num, num_step):
    """Returns every number from 0 to max_num with num_step as step."""
    n = 0
    l = []

    while n < max_num + 1:
        l.append(n)
        n += n * num_step

    return l

n_l = []
n_l.append(numbers_calc(25, 1))

print "Here are the numbers."
print n_l

The function numbers_calc is meant to take all the given args, form a list, and populate it with numbers (with num_step as the step when calculating) before it reaches max_num + 1. The script then does return it's local list named l.

However, every time I run the script, I encounter MemoryError. Here's what Python returned when I ran the script:

Traceback (most recent call last):
File "num.py", line 13, in <module>
    n_l.append(numbers_calc(25, 1))
  File "ex33.py", line 7, in numbers_calc
    l.extend(i)
MemoryError

I tried looking it up, saw nothing helpful. I hope you can help me!


1 Answers

n starts at 0. n += n * num_step adds 0 to n. n never changes, and your loop keeps adding items to the list forever.

Cause n to change somehow.

like image 73
Ry- Avatar answered Aug 28 '26 14:08

Ry-