Python lists don't grow automatically; addressing indexes that don't exist does not work. You'd normally use .append()
for that:
T_1 = []
for a in A_1:
nested = []
T_1.append(nested)
for y in y_1:
nested.append(T0_1 + ((q0_1 / k_1) * y) - (a / (2 * k_1)) * y**2))
Note that you don't need to create indices anymore; you can loop directly over A_1
and y_1
and use the values in the formula.
The alternative would be to create an empty structure with placeholder values; like None
:
T_1 = [[None] * len(y_1) for _ in range(len(A_1))]
for i, a in enumerate(A_1):
for j, y in enumerate(y_1):
T_1[i][j] = T0_1 + ((q0_1 / k_1) * y) - (a / (2 * k_1)) * y**2))
Here I used enumerate()
to add an index to each loop; this lets you have your cake and eat it; access a value from an input sequence and its location in the sequence.
However, your nested lists can most simply be generated with a nested set of list comprehensions:
T_1 = [[T0_1 + ((q0_1 / k_1) * y) - ((a / (2 * k_1)) * y**2) for i in y_1] for a in A_1]
Here [expression for variable in iterable]
executes the expression on the left-hand side for each iteration of the loop. The outer loop over A_1
generates a new list for each a
in the loop. That new list is itself a list comprehension, looping over y_1
and generating new values (your formula) for each element.
Note that now we no longer need to generate indices or use list.append()
each loop iteration. The lists are built in-place.