Reputation: 13
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
Upvotes: 1
Views: 301
Reputation: 2738
You're correct, you shouldn't iterate over a list while editing. But as pointed by other users, none of the above examples are iterating over the list lst
.
Here is an example of iteration:
for item in lst:
# Do something
If you need to iterate over a list while editing it, make a copy and iterate over the copy:
copy_lst = lst[:]
for item in copy_lst:
# edit lst
I'd stick with the following code:
def appendsums(lst, times):
for i in range(times):
lst.append(sum(lst[-3:]))
return lst
Upvotes: 2
Reputation: 563
Its generally unsafe because iterators on the container aren't informed that a change has occurred. You usually want to create a temporary list and then modify the target list at the end.
Also, as a side note, I think you may want count to be less than times (and not equal to it).
In its current form, when I set times to 5, it adds six entries.
>>> def appendsums(lst, times):
... count = 0
... while count <= times:
... sums = sum(lst[-3:])
... lst.append(sums)
... count += 1
... return lst
...
>>> appendsums([1,2,3], 5)
[1, 2, 3, 6, 11, 20, 37, 68, 125]
Upvotes: 2