Algorithms & data structures
Classic patterns — search, sort, stacks, queues, and practical complexity-aware code.
How to Combine filter and map with a List Comprehension in Python
This Python code demonstrates how to combine filtering and mapping in a single list comprehension and shows the equivalent filter() and map() approach.
def square(x):
return x * x
def is_even(x):
return x % 2 == 0
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
result = [square(x) for x in numbers if is_even(x)]
print(f"Original numbers: {numbers}")
print(f"Squares of even numbers: {result}")
# Combined filter + map equivalent
filtered = filter(is_even, numbers)
mapp…
How to Find Four Sum Quadruplets in Python (Sorted Demo)
Find all unique quadruplets in a sorted array that sum to a target, with duplicate skipping.
def four_sum(nums, target):
nums.sort()
result = []
n = len(nums)
for i in range(n - 3):
if i > 0 and nums[i] == nums[i - 1]:
continue
for j in range(i + 1, n - 2):
if j > i + 1 and nums[j] == nums[j - 1]:
continue
left, right = j + 1…
How to Find the n Smallest Items in a Large List with heapq in Python
This code demonstrates how to efficiently extract the n smallest items from a large list using Python's heapq module and a manual max-heap approach.
import heapq
def n_smallest_iterable(data, n):
"""Return the n smallest items without loading the whole list."""
if n <= 0:
return []
return heapq.nsmallest(n, data)
def n_smallest_manual(data, n):
"""Return the n smallest using a heap, O(n log k) time."""
if n <= 0:
return []
…
Set Matrix Zeroes in Python: Markers List Grid Demo
Given a matrix, this code finds all rows and columns that contain a zero and sets every element in those rows and columns to zero, using boolean marker arrays.
def set_zeroes(matrix):
rows, cols = len(matrix), len(matrix[0])
row_markers = [False] * rows
col_markers = [False] * cols
# First pass: record which rows and columns contain zeros
for i in range(rows):
for j in range(cols):
if matrix[i][j] == 0:
row_markers[i] …
Split a String into Multiple Lines by Width in Python
Demonstrates a word-wrap algorithm that splits a message into rows without exceeding a maximum width.
def split_message(text, max_width):
words = text.split()
rows = []
current_row = []
for word in words:
if len(" ".join(current_row + [word])) > max_width:
rows.append(" ".join(current_row))
current_row = [word]
else:
current_row.append(word)
if …
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.