I want to store the intermediate values of a variable in Python. This variable is updated in a loop. When I try to do this with a list.append
command, it updates every value in the list with the new value of the variable. How should I do it ?
while (step < maxstep):
for i in range(100):
x = a*b*c
f1 += x
f2.append(f1)
print f2
raw_input('<<')
step += 1
Expected output
[array([-2.03,-4.13])]
<<
[array([-2.03,-4.13]),array([-3.14,-5.34])]
Printed output
[array([-2.03,-4.13])]
<<
[array([-3.14,-5.34]),array([-3.14,-5.34])]
Is there a different way of getting what I want in python?
The Python List append() method is used for appending and adding elements to the end of the List. Parameters: item: an item to be added at the end of the list.
Python's append() function inserts a single element into an existing list. The element will be added to the end of the old list rather than being returned to a new list. Adds its argument as a single element to the end of a list.
Definition and Usage The append() method appends an element to the end of the list.
Assuming the original had a typo and f1
is actualy fi
(or vice verca):
fi
is a pointer to an object, so you keep appending the same pointer, when you fi += x
you actually changing the value of the object to which fi
points. Hope this is clear.
To solve the issue you can fi = fi + x
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With