(Apr-24-2017, 03:43 AM)nilamo Wrote: Modifying a list while you're in the middle of iterating over that same list is very dangerous.Usually - from the last time I SNAFUed this way (several years ago ) - iterator skips element on each deletion. It's not dangerous - it's a bug
(Apr-23-2017, 10:19 AM)smbx33 Wrote: I made minor modifications to the existing code and provided explanation.Though it works - as I have pointed out in previous post, deleting an element of a list while iterating over that list is a bug, which is in this case accidentally compensated for by the external loop. In another scenario, it will not work as expected
..... while len(list_) >0: # here you had list[0] I think you wanted to stop when length reached 0 for amount in list_: # for loop will go through the list_ of numbers one amount at a time ..... list_.remove(amount) #this is to remove items from your list! # you don't need to check the counter. so the if statement could be deleted or reworded so if the program is run and no items are on the list it says NO ITEMS! else it prints A
This solves the issue
while list_: s += list_[0] ..... list_.pop(0)This way you always process first element of the list - while list is not empty, and you don't perform any unnecessary actions
Test everything in a Python shell (iPython, Azure Notebook, etc.)
- Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
- Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
- You posted a claim that something you did not test works? Be prepared to eat your hat.