Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list append

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?

like image 700
abcd Avatar asked Sep 05 '12 10:09

abcd


People also ask

Is append a list function 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.

What is the use of append () in list give example?

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.

What is append in Python with example?

Definition and Usage The append() method appends an element to the end of the list.


1 Answers

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.

like image 185
zenpoy Avatar answered Sep 29 '22 01:09

zenpoy