I have a list of objects like this [bpy.data.objects["Text.002], bpy.data.objects["Text.003], bpy.data.objects["Text.005], bpy.data.objects["Text.007]] how can I sort them by their distance from a point like for example p =(0, 0, 0)?

I've tried to calculate the distance from two points in the 3d space using the origin and the point coordinates, but then how can I sort the objects?


There are a number of ways to sort lists in python. Here is one using lambda.

import bpy
from mathutils import Vector
# some list of objects (taken from q)
objects = [bpy.data.objects["Text.002"],
# sort by location from (0, 0, 0)
objects.sort(key=lambda o: o.location.length)
# sort by visual location from (0, 0, 0)
# eg objects moved by constraint / parenting etc.
objects.sort(key=lambda o:

v = Vector((1, 2, 3))
# sort by distance from v
objects.sort(key=lambda o:
             (o.matrix_world.to_translation() - v).length)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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