Algorithms & data structures
Classic patterns — search, sort, stacks, queues, and practical complexity-aware code.
Drop Elements From Start While Condition Is True in Python
This generator function drops elements from the beginning of an iterable while a predicate returns true, then yields the rest.
def drop_while(predicate, iterable):
"""Drop elements from the start while predicate is true."""
it = iter(iterable)
for item in it:
if not predicate(item):
yield item
break
yield from it
if __name__ == "__main__":
numbers = [1, 2, 3, 4, 1, 2, 5]
result = list(d…
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.
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…
How to Find the Nearest Value to a Target in a Sorted List in Python
Use bisect to binary-search a sorted list and return the element closest to a target value.
import bisect
def nearest_value(sorted_list, target):
if not sorted_list:
return None
pos = bisect.bisect_left(sorted_list, target)
if pos == 0:
return sorted_list[0]
if pos == len(sorted_list):
return sorted_list[-1]
before = sorted_list[pos - 1]
after = sorted_list[po…
Browse by section
Each section groups closely related Python snippets.
Algorithms & data structures — Python code examples
What you will find here
This page collects algorithms & data structures snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.