Need A Simple Code :)

Hey! I have an object contains only vertex. In the edit mode I sorted them view x axis in top view. I need a code that will make edge following this order. So the very first vertex and the second one will form an edge and so on. Hope I am clear and hope someone can code this. I don’t know about coding but this one seemed easy to me, please help guys.

Here’s a simple code, fully commented.
It gets the vertices, sorts them in ascending x position and creates edges.
Select your object (stay in object mode) and run the code.


import bpy
import bmesh


obj = bpy.context.object # get selected active object


if obj.type == 'MESH': # check if the object is a mesh
    me = obj.data # get the object data


    bm = bmesh.new() # create empty bmesh
    bm.from_mesh(me) # fill it in from the object mesh


    verts = list(bm.verts) # get the verts
    verts.sort(key=lambda v: v.co.x) # sort the verts by ascending x coordinate


    for i in range(len(verts)-1): # loop through verts
        bm.edges.new((verts[i], verts[i+1])) # create edge between 2 verts
        
    bm.to_mesh(me) # write the bmesh back to object mesh
    bm.free() # free and prevent further acces


# do something to update the 3D viewport

If you questions about the code feel free to ask !

Thanks! That is just what I was looking for.