I have just started learning Python so i just wanted to get something straight. I want to make a function that repeatedly appends the sum of the current last three elements of the list "lst" to "lst", x number of "times". As far as i understand you should not change a list while iterating over it, so my second solution is wrong, right? Even though it produces the same result as the first function?
def appendsums(lst, times): count = 0 for i in range(times): if count <= times: sums = sum(lst[-3:]) lst.append(sums) count += 1 return lst Here is my second solution
def appendsums(lst, times): count = 0 while count <= times: sums = sum(lst[-3:]) lst.append(sums) count += 1 return lst Regards
countor any checking e.g.count <= timescount <= timescheck is wrong in both versions; if you count from0totimes, that'stimes+1values ofcountandtimes+1loop iterations. It should becount < timesin the second version and removed entirely in the first, since theforloop makescountredundant.