I am trying to calculate a moving average of a list called 'temp_data' in the function below. The moving average data should be stored in a list called 'moving_average'. The code below works in the sense that list 'temp_mov' is printed inside the function (line 12), but not when I call the function later on (in the last line of the code). In that case, I get an empty list. What mistake do I make?
# calculate moving average of a list of weather data
def make_moving(temps, temp_mov):
''' Create moving average from list weather data'''
cumsum, temp_mov = [0], []
for i, x in enumerate(temps, 1):
cumsum.append(cumsum[i-1] + x)
if i>=N:
moving_ave = round((cumsum[i] - cumsum[i-N])/N, 1)
temp_mov.append(moving_ave)
print(temp_mov)
return temp_mov
make_moving(temp_data, moving_average)
print(moving_average)
You assign a new list to temp_mov
here:
cumsum, temp_mov = [0], []
Therefore, moving_average
is not updated when temp_mov
changes.
Changing make_moving(temp_data, moving_average)
to moving_average = make_moving(temp_data)
and removing the temp_mov
parameter will solve the problem.