Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Loop skips every second item when removing selected items from many to many

In my application I am trying to remove many to many records via loop:

org = current_user.Organization
for item in org.items:
        if item.id in remove_ids:
            org.items.remove(item)
db.session.commit()

However, it skips every second item. Since the list is modified in the loop. How could I solve it in a proper way?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Removing elements from a container in a loop typically doesn’t work.

I would suggest something along the lines of:

org = current_user.Organization
org.items = [item for item in org.items if item.id not in remove_ids]
db.session.commit()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading