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.
Python code
12 linesimport 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
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
- Use `points.sort(key=lambda p: p[0]**2 + p[1]**2)` to avoid the sqrt call for better performance.
- 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
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.