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…
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.