Algorithms & data structures
Classic patterns — search, sort, stacks, queues, and practical complexity-aware code.
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…
Insert Multiple Values Into a Sorted List in Python
Insert multiple values into an already-sorted list while keeping it sorted using the bisect.insort function.
import bisect
def insert_sorted(sorted_list, values):
for value in values:
bisect.insort(sorted_list, value)
return sorted_list
if __name__ == "__main__":
original = [1, 3, 5, 7, 9]
new_values = [4, 6, 2, 8, 0]
result = insert_sorted(original, new_values)
print(f"Original: {original}"…
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.