14

I'm facing a rather easy to solve problem but I just don't know how to do it. I want blender to list all the objects selected as a string. Eg. if I run :

selection_names = bpy.context.selected_objects
print (selection_names)

it gives me this line:

[bpy.data.objects['Cube.003'], bpy.data.objects['Cube.002'], bpy.data.objects['Cube.001'], bpy.data.objects['Cube']]

But what I want is for selection_names is to print out as:

['Cube.001','Cube.002','Cube.003','Cube']

2 Answers 2

13

The fastest way to solve this is through list comprehension :

selection_names = [obj.name for obj in bpy.context.selected_objects]

which is the exact equivalent of:

selection_names = []
for obj in bpy.context.selected_objects:
    selection_names.append(obj.name)
0
11
>> selection_names = bpy.context.selected_objects
>>> print (selection_names)
[bpy.data.objects['Armature 05.04 p'], bpy.data.objects['Armature 04.08 l'], bpy.data.objects['Armature 04.07 p'], bpy.data.objects['Armature 04.07 l'], bpy.data.objects['Armature 04.04 p'], bpy.data.objects['Armature 04.05 p'], bpy.data.objects['Armature 04.05 l']]

>>> for i in selection_names:
...     print(i.name)
...     
Armature 05.04 p
Armature 04.08 l
Armature 04.07 p
Armature 04.07 l
Armature 04.04 p
Armature 04.05 p
Armature 04.05 l

If you want them to become objects in an array, you can do this:

>>> SelNameArr=[]
>>> for i in selection_names:
...     SelNameArr.append(i.name)
...     
>>> SelNameArr
['Armature 05.04 p', 'Armature 04.08 l', 'Armature 04.07 p', 'Armature 04.07 l', 'Armature 04.04 p', 'Armature 04.05 p', 'Armature 04.05 l']
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.