How does Lloyd's algorithm for k-means work step-by-step?

Last updated 11 November 2026

Lloyd's algorithm alternates between assigning points to their nearest centroid and recomputing centroids as cluster means, repeating until assignments stop changing. Each step lowers the within-cluster sum of squares.

  1. Initialize: Choose k initial centroids (random points or, better, k-means++).

  2. Assignment step:

    • Assign each point to the centroid with the smallest squared Euclidean distance (a Voronoi partition).

    • Optimal for fixed centroids.

  3. Update step:

    • Set each centroid to the mean of its assigned points.

    • Optimal for fixed assignments. Handle empty clusters (e.g. reseed with the farthest point).

  4. Repeat until convergence: Stop when assignments don't change, centroid movement < tolerance, or max iterations reached.

  • Properties:

    • Cost per iteration: O(n·k·d); usually converges in few iterations.

    • Guaranteed to converge (finite partitions, monotone objective) but only to a local minimum, so results depend on initialization.

[lang:python] import numpy as np def lloyd(X, C, iters=100): for _ in range(iters): labels = ((X[:, None] - C[None]) ** 2).sum(-1).argmin(1) # assign newC = np.array([X[labels == j].mean(0) for j in range(len(C))]) # update if np.allclose(newC, C): break C = newC return labels, C

  • https://en.wikipedia.org/wiki/K-means_clustering
  • https://scikit-learn.org/stable/modules/clustering.html
  • https://buildml.substack.com/p/data-scientists-interview-guide-k-means-56135e9e47b9
All Clustering interview questions