For loop help


(Way2Close) #1

What am I doing wrong lol, I make a list of selected objects and want to .remove them from the list if they are not a mesh or a curve, but if I make 3 suns and run the script it doesn’t remove them all :S


import bpy 


selected_objects = bpy.context.selected_objects


print("-----------------------------")
print("List len before: " + str(len(selected_objects)))


for obj in selected_objects:
      
    if obj.type not in ['MESH','CURVE']:
        selected_objects.remove(obj)


print("List len after: " + str(len(selected_objects)))


(Secrop) #2

If you remove the items from the beginning of a list, the index of the next item will be now the index of the removed item… The for loop just keeps the track of the index it’s iterating, and it will jump to the index+1, thought the next item is now at index0.

you can try do change it to this instead:


my_filtered_objects=[obj for obj in selected_objects if obj.type in ['MESH', 'CURVE']]


(Way2Close) #3

Thank you very much, I was just trying to be optimized and use one variable. Guess I need to read up on arrays haha