Algorithms & data structures
Classic patterns — search, sort, stacks, queues, and practical complexity-aware code.
Find Elements in One Python List but Not Another
Return a new list containing only the elements from list A that are not present in list B, preserving duplicates and order.
def difference_elements(a, b):
"""Return elements present in list a but not in list b."""
set_b = set(b)
return [item for item in a if item not in set_b]
if __name__ == "__main__":
a = [1, 2, 3, 4, 5, 3, 2]
b = [2, 4, 6]
result = difference_elements(a, b)
print(f"A: {a}")
print(f"B: {b…
Find Missing Number in Python Sequence 1 to N
Find the missing number from a list containing numbers 1 to N using the arithmetic sum formula.
def find_missing_number(nums, n):
expected_sum = n * (n + 1) // 2
actual_sum = sum(nums)
return expected_sum - actual_sum
if __name__ == "__main__":
n = 10
numbers = [1, 2, 3, 4, 5, 6, 7, 9, 10]
missing = find_missing_number(numbers, n)
print(f"The missing number is: {missing}")
How to Build a Coordinate Grid with Nested Loops in Python
Generate a 2D list of (row, col) coordinate pairs using nested loops and return the grid structure.
def build_coordinate_grid(rows, cols):
"""Build a 2D grid of (row, col) coordinates using nested loops."""
grid = []
for r in range(rows):
row = []
for c in range(cols):
row.append((r, c))
grid.append(row)
return grid
if __name__ == "__main__":
grid = build_coo…
How to Compute the Cartesian Product of Two Lists in Python
Generates all ordered pairs from two lists using itertools.product and prints each combination.
from itertools import product
# Two small input lists
list_a = [1, 2, 3]
list_b = ["x", "y"]
# Compute the Cartesian product
result = list(product(list_a, list_b))
# Display the result
print("Cartesian product of", list_a, "and", list_b, "is:")
for pair in result:
print(pair)
How to Find Gaps Between Sorted Intervals in Python
This code finds gap ranges between sorted intervals using pairwise iteration, returning ranges where no interval covers.
from itertools import pairwise
def find_gaps(intervals):
intervals = sorted(intervals)
gaps = []
for prev, curr in pairwise(intervals):
if prev[1] < curr[0]:
gaps.append((prev[1] + 1, curr[0] - 1))
return gaps
if __name__ == "__main__":
intervals = [(1, 3), (5, 7), (10, 12), (…
How to partition a list into n nearly equal parts in Python
Divide a list into n contiguous chunks of nearly equal size using an average-length calculation that distributes the remainder evenly.
def partition(lst, n):
"""Partition a list into n nearly equal contiguous parts."""
if n <= 0:
raise ValueError("n must be positive")
if not lst:
return [[] for _ in range(n)]
parts = []
avg = len(lst) / n
last_idx = 0.0
while last_idx < len(lst):
end_idx =…
Merge Two Sorted Arrays Without Extra Space in Python
Merge two sorted arrays in-place from the end, using the trailing zeros in the first array to avoid extra space.
def merge_sorted(arr1, arr2):
m, n = len(arr1), len(arr2)
i, j = m - 1, n - 1
while j >= 0:
if i >= 0 and arr1[i] > arr2[j]:
arr1[i + j + 1] = arr1[i]
i -= 1
else:
arr1[i + j + 1] = arr2[j]
j -= 1
return arr1
if __name__ == "__main__":
…
Move Zeroes to End in Python Maintaining Order
In-place algorithm that moves all zeroes to the end of a list while preserving the relative order of non-zero elements.
def move_zeroes(nums):
non_zero_index = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[non_zero_index], nums[i] = nums[i], nums[non_zero_index]
non_zero_index += 1
return nums
if __name__ == "__main__":
example = [0, 1, 0, 3, 12]
result = move_zeroes(example)
…
Pair Elements with Next Cyclic Neighbor in Python
Create tuples pairing every element with its next element, wrapping around to the first element for the last one.
def cyclic_pairs(lst):
if not lst:
return []
return [(lst[i], lst[(i + 1) % len(lst)]) for i in range(len(lst))]
if __name__ == "__main__":
sample = [1, 2, 3, 4, 5]
result = cyclic_pairs(sample)
print(result)
Stable merge two lists by custom comparator in Python
Merge two lists into one sorted output using a custom comparator while maintaining the original order of equal elements.
from functools import cmp_to_key
def compare(x, y):
# Custom comparator: sorts by length first, then by original index for stability
if len(x) != len(y):
return len(x) - len(y)
return 0 # Equal keys preserve original order (stable)
def merge_stable(left, right, cmp_func):
result = []
i =…
Stable sort preserving equal order demo in Python
Demonstrates Python's stable sort, showing that elements with equal sort keys retain their original relative order.
from operator import itemgetter
def stable_sort_demo():
data = [(3, "first"), (1, "second"), (3, "third"), (1, "fourth"), (2, "fifth")]
print("Original:", data)
# Sort by first element (the tuple's first value), keeping relative order of equal items
sorted_data = sorted(data, key=itemgetter(0))
…
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.