I need to store 10 data frames into a list. The data frames are the outputs of a function. The problem is that the list remains all the same as the last data frame. For example, resultlist[0] suppose to be the data frame of 01-Feb-2020. But every data frame in the list is the output from 10-Feb-2020.
resultList = [None]*10
for i in range(0,10):
resultList[i]= getResultfunction(id,listDates[i])
As far as I can see, the code snippet you provided is correct. Just know that you are giving the same id parameter to each getResultfunction call. Could you show the implementation of the getResultfunction? The problem is probably in there. Either that or your listDates list contains the wrong dates.
EDIT 1 Alright so the problem is probably that you are just storing references to the same dataframe in the list. If you are not familiar with how programming languages store references and values, I'd suggest that you check out this link https://blog.penjee.com/passing-by-value-vs-by-reference-java-graphical/ or just google it, as its a fundamental paradigm of programming languages.
So basically, each time you call getResultfunction
, you get a reference to the same template, then you alter this template, and return a reference to the template. Next time you call the function, you access the same (altered) template, change it again, and return a new reference to it. The list then stores lots of references to the same object!
In this particular case, each call to getResultfunction should create a new object. I see 2 solutions; Each time you call getResultfunction you:
def getResultfunction(id, date):
p = template.copy()
"""other computations"""
return p
def getResultfunction(id, date):
data = {...}
df = pd.Dataframe(data)
""""other computations"""
return df