I am working on a simple math problem that requires me to find a list of Sval values per k per w value. I have this nested for loops.
w = [0,1/3,-1]
k = [0,-1]
S = 0.001
Sval = [S]*30
Sval_list = []
for wval in w:
for kval in k:
for i in range(1, 30):
Sval[i] = Sval[i-1] wval-kval
print("{},{}".format(wval,kval),Sval)
Sval_list.append(Sval)
The loops is expected to loop for six times, each loop would output a list of Sval. I expected an outcome of a list with shape(6,30), which I got. But it is appending the output list from 6th loop for six times, instead of appending one output list per loop. Any help to solve this question or to make my codes neater is welcomed!
CodePudding user response:
At the end of the program, Sval_list
contains six copies of Sval
(a list), since you appended it 6 times. Each time you run through the inner most for
loop and modify Sval
, it modifies all copies of Sval
in Sval_list
since that's how lists work in python, and that's why all lists in Sval_list
are the same at the end.
You can fix this by effectively detaching each Sval
when you append it to Sval_list
. Instead of writing Sval_list.append(Sval)
, write Sval_list.append(list(Sval))
. The list
will create a new list that no longer changes when you change Sval
.
CodePudding user response:
your mistake is in using the reference, by appending the Sval
reference to the Sval_list
.
you get a shallow copy of Sval
as value and with change of Sval
, all your data would be changed. appending a hard copy of Sval
to the Sval_list
would do the job:
Sval_list.append(Sval[:])