# How to select objects by collection from selected objects in the scene with Python?

I just started using python and got stuck. I found this script which is used to take the selected objects from the scene and add them to a list based on the name of the material. I should do almost the same thing but based on the name of the collection, rather than that of the material. Can you help me? Thanks in advance.

selection = bpy.context.selected_objects
obj_list = []
for o in selection:
for m in o.material_slots:
if '_abetemono15' in m.name:
obj_list.append(o)


More explanations.

Thanks brockmann, Yes, well it is difficult to explain. However I try. I am a designer for a carpentry shop. In Blender I have not found a way to calculate the quantities of lumber and things like that. In recent days I have written things like this:

It was a nightmare. In addition to not understanding Python, I also struggle with English. I'm good at Blender but this time is not enough. However this thing works, but I had to use the materials to separate the types of timber that are used in the furniture. But this doesn't work because sometimes I have to replace the surface material without changing the name of the material that is related to the script. Probably the best thing to do is to use collections to group material types, materials for materials and emptys to group furniture.

I found this. But it works without considering the selection on the scene.

selection = bpy.data.collections["Abete massiccio"].objects

• Hi daniele! Please elaborate on your goal. You'd like to get all objects in the scene based on the name of the collections their are in? Can you please add an example to your question? May 10 '20 at 18:00
• Thanks brokmann, I extended my question. I'm looking for a way to post the blend file I'm working on ... May 10 '20 at 18:45
• Oh, cool. I didn't know about this service. Thanks. Now I have added the .blend file May 10 '20 at 19:57

## 1 Answer

Sample script based on your collection name.

import bpy

sel_objs = bpy.context.selected_objects

#identify and choose collection union
col = bpy.data.collections["Abete massiccio"]

# create a list requiring both objects selected and in chosen collection
objs_in_col = [obj for obj in col.objects if obj in sel_objs]

for obj in objs_in_col:
print("Object name: %s \t Collection: %s" %(obj.name, col.name))

• Good candidate for sets set(C.selected_objects).intersection(set(C.collection.objects)) May 10 '20 at 23:11
• @batFINGER Thanks for the tip wasn't sure how to easily convert the lists to allow .intersection().
– Ratt
May 10 '20 at 23:32
• or o for o in C.collection.objects if o.select_get(True) would be another way. .... avoids using multiple in checks. May 11 '20 at 1:04
• It works! You saved my life. I could never have thought of this. Thanks a lot Ratt. May 11 '20 at 6:55