Search code examples
pythonfor-loopenumerate

Is it safe to modify elements inside an enumerate() loop if it is followed by a break?


I've written some python code which loops through a list like below:

for idx, r in enumerate(mylist):
    if condition:
        del mylist[idx]
        break

My question is, whether it is safe to modify this list inside the loop (like in the above example) as long as I have that break statement? Or should I still be modifying the list outside of the loop?


Solution

  • Yes it is safe if this code is not concurrent if other threads are not going to use mylist concurrently. But as long as we have GIL I think it safe to do it. Better way is to wrap it in a function and return a new copy this way it will be side effects free

    def create_my_list(mylist):
      mylist = mylist[:] #to create local copy as mylist is passed by reference
      #mylist is a localcopy here
      for idx, r in enumerate(mylist):
          if condition:
            del mylist[idx]
            break
      return mylist