Find k Closest Points to Origin in Python

Sorts a list of (x, y) point tuples by their Euclidean distance from the origin and returns the k nearest points.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 13 views 0 copies

Python code

12 lines
Python 3.9+
import math

def k_closest(points, k):
    points.sort(key=lambda p: math.sqrt(p[0]**2 + p[1]**2))
    return points[:k]

if __name__ == "__main__":
    points = [(1, 2), (3, 4), (-1, 0), (5, 5), (0, 1)]
    k = 3
    result = k_closest(points, k)
    print(f"Original points: {points}")
    print(f"K closest points (k={k}): {result}")

Output

stdout
Original points: [(1, 2), (3, 4), (-1, 0), (5, 5), (0, 1)]
K closest points (k=3): [(-1, 0), (0, 1), (1, 2)]

How it works

The sort method sorts the list in place using a key function that computes the Euclidean distance math.sqrt(x**2 + y**2) for each tuple. Since the sorting is stable, tuples with equal distance retain their original order. Slicing with points[:k] returns the first k elements after sorting. The math.sqrt call is used for clarity, but you could omit it because squaring the distance preserves order. This approach is simple and works well for moderate-sized lists.

Common mistakes

  • Forgetting to import math or using `p[0] ** 2 + p[1] ** 2` without the square root when comparisons are not order-preserving.
  • Returning a slice that includes more than k points when k exceeds the list length.
  • Modifying the original list when you need to preserve it — use `sorted(points, key=...)` to avoid side effects.
  • Using `math.hypot(p[0], p[1])` but forgetting to import math — it is part of the stdlib.

Variations

  1. Use `points.sort(key=lambda p: p[0]**2 + p[1]**2)` to avoid the sqrt call for better performance.
  2. Implement with `heapq.nsmallest(k, points, key=lambda p: p[0]**2 + p[1]**2)` for O(n log k) time and no full sort.

Real-world use cases

  • Location-based services returning the nearest venues to a user's coordinates from a small candidate list.
  • Geospatial clustering pre-step to find the k closest sensor nodes to a reference point.
  • Game development selecting the nearest enemies or pickups based on a player's position.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.