Home > Mobile >  Appending the output of a 'for' loop to a list (Python)
Appending the output of a 'for' loop to a list (Python)

Time:10-15

I'm new to Python, and am just grasping the concept of the 'for' loop. I have generated a loop to print out several differences, but I cannot seem to append all of them to a list.

Here is the code I have thus far:

# Question 1
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
from scipy.interpolate import CubicSpline
from numpy import log


y0 = [10,1] # [Prey, Predator] units in hundreds

pd = [100,200,300,400,500,600,700,800,900,1000, 1100, 1200,
     1300,1400,1500,1600,1700,1800,1900,2000]

for x in pd:
    t = np.linspace(0.,50.,num=x) 

    alpha = 0.1
    beta = 0.02
    gamma = 0.4
    delta = 0.02

    params = [alpha, beta, delta, gamma]

    def sim(variables, t, params):

        # Prey population level
        x = variables[0]

        # Predator population level
        y = variables[1]


        alpha = params[0]
        beta = params[1]
        delta = params[2]
        gamma = params[3]

        dxdt = alpha * x - beta * x * y
        dydt = delta * x * y - gamma * y

        return([dxdt, dydt])


    y = odeint(sim, y0, t, args=(params,))

    lv_prey = y[:,0] # saving prey population separately
    lv_pred = y[:,1] # saving predator population separately

    prey_array = np.array(lv_prey) 
    pred_array = np.array(lv_pred)

    # Fit a cubic spline
    num_pts = 10
    tsp = np.array([t[i] for i in range(0, len(t), len(t)//num_pts)])

    # Prey
    prey_sp = np.array([lv_prey[i] for i in range(0, len(t), len(t)//num_pts)])
    Curve1 = CubicSpline(tsp, prey_sp, bc_type = 'natural', extrapolate = False)

    # Predator
    pred_sp = np.array([lv_pred[i] for i in range(0, len(t), len(t)//num_pts)])
    Curve2 = CubicSpline(tsp, pred_sp, bc_type='natural', extrapolate=False)

    prey_extrap_dots=Curve1(tsp)
    prey_extrap_line = Curve1(np.array([tt for tt in t if tt<=tsp[-1]]))
    pred_extrap_dots=Curve2(tsp)
    pred_extrap_line=Curve2(np.array([tt for tt in t if tt<=tsp[-1]]))

    # Fit the invariate for the Lotka-Volterra model
    Cspline = alpha*np.log(pred_extrap_line) - beta*(pred_extrap_line) - delta*(prey_extrap_line)   gamma*np.log(prey_extrap_line)
    diff = np.max(Cspline) - np.min(Cspline)
    diffList = []
    diffList.append(diff)
    print("The difference is {}".format(diff))

When I call the diffList command, only the last output of the loop is appended.

How can I append the diff values to a list?

CodePudding user response:

You are resetting diffList to an empty list every time just before you append diff in your 3rd last line. You should move this initialization to before the for loop so it only happens once:

diffList = []

CodePudding user response:

you should call empty diffList before the for loop

CodePudding user response:

Your code is doing something like this:

for i in range(10):
    squares = []
    squares.append(i * i)

What is happening is that for every iteration of the for-loop a new empty list squares is created. That means that after the loop is over squares will only contain the value appended on the last iteration.

Instead create your list before your for-loop:

squares = []
for i in range(10):
    squares.append(i * i)
  • Related