https://python-forum.io/thread-670.html Wrote:Modifying a list (or other container) while iterating over it
for laser in lasers: ... if rm: lasers.remove(laser)This will cause an IndexError when you iterate over the loop as you have just removed an index from the list that you are looping over. A catch 22. You need to loop the list in order to remove, but you cannot remove from the list as you loop. This can be easily fixed by looping a copy of the list and removing from the actual list. All you have to do to loop a copy is add[:]
.
for laser in lasers[:]: ... if rm: lasers.remove(laser)The [:] is a shallow copy. The is identical to using the copy module forcopy.copy()
. If you have nested structures you may want a deep copy. This you are going to need to usecopy.deepcopy()
See more info here
deleting select items from a list
Users browsing this thread: 2 Guest(s)