Modify a List within a loop

Hi all,
We have two lists of points with identical lengths.
For each point in List1, I want my code to search for the closest point in List2.
Once a point is selected from List2, it no longer can be picked by other points of List1.
My code generates 6 lines instead of 3.
I know List2 has to be updated in one way or another.
Appreciate it if someone highlights what I am doing wrong in my code, (9.3 KB)
test01.3dm (52.0 KB)


I think you just need to unindent 3 lines from list=min... by one level.

Or you could use

Hi Graham,
Unindenting those lines does not help, whereas it says " index out of range" when moving the points.
Also, the link you provided, finds the closest point but does not knock it off the List2 after assignment.
As a result, one point in List2 can be assigned to multiple points in List1.

Hmmm… you also need to move dist = [] inside your i loop… doe that fix it ?

Thanks a lot,

Here’s an alternative way to achieve this.

import Rhino.Geometry as rg

def point_closest_point(pt, pts_list):
    """Finds the closest point in a collection of points.
      pt (Rhino.Geometry.Point3d): A point to search from.
      pts_list (list): A collection of points to search.
      The closest point.
    closest_dist = float("inf") # infinity
    closest_idx = -1
    for i in xrange(len(pts_list)):
        dist = pt.DistanceTo(pts_list[i])
        if dist < closest_dist:
            closest_dist = dist
            closest_idx = i
    if closest_idx >= 0:
        return closest_idx

y_pts = y[::] # temporary list
lines = []

for i in range(len(x)):
    closest_idx = point_closest_point(x[i], y_pts)
    lines.append(rg.Line(x[i], y_pts[closest_idx]))  

a = lines
1 Like