1

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

3
  • 7
    You're not iterating over the list in either version, so I don't see what the problem's supposed to be. Commented Jun 13, 2014 at 17:55
  • In first solution you don't need count or any checking e.g. count <= times Commented Jun 13, 2014 at 17:59
  • The count <= times check is wrong in both versions; if you count from 0 to times, that's times+1 values of count and times+1 loop iterations. It should be count < times in the second version and removed entirely in the first, since the for loop makes count redundant. Commented Jun 13, 2014 at 18:01

2 Answers 2

2

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 
Sign up to request clarification or add additional context in comments.

3 Comments

There is no need to slice the list, since we only append after the sum is complete.
The slice is because we only want the last 3 elements, not because we're worried about changing the list while iterating over it.
Oh, I missed that point in the question. Sorry, I'm fixing. Thanks.
2

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] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.