Best way to find the 2 closest vertices from a list of vertices?
Naively, this creates a look-up list of closest vertex indices.

import mathutils
import bpy

ob = bpy.context.object

# create a kd-tree from a mesh
me = ob.data
size = len(me.vertices)
kd = mathutils.kdtree.KDTree(size)
for i, v in enumerate(me.vertices):
    kd.insert(v.co, i)
kd.balance()

# create ordered list of closest vertex indices
closest_vIdx = []
for v in me.vertices:
    co_find = v.co
    closest_2 = kd.find_n(co_find,2)
    closest_vIdx.append(closest_2[1][1])

#Insert the index of the queried vertex here:
vIdx = 5707

print (f"vertex:{vIdx} closest vertex:{closest_vIdx[vIdx]}")


Bear in mind with this one:


The distances are in 3-space, not necessarily down edges.
Only the 'first' of any set of equidistant vertices is chosen


You wouldn't want to build the KDTree (or the closest list) more often than necessary - the best way of finding the closest vertex may depend on exactly if/when you want to modify the mesh, and would therefore have to rebuild the tree.