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 the Second Largest Unique Number in a Python List
This Python function finds the second largest unique number from a list by converting it to a set, removing the maximum, and returning the new maximum.
def second_largest_unique(numbers):
unique_numbers = set(numbers)
if len(unique_numbers) < 2:
return None
unique_numbers.remove(max(unique_numbers))
return max(unique_numbers)
if __name__ == "__main__":
test_list = [4, 2, 9, 5, 2, 9, 1, 5]
result = second_largest_unique(test_list)
…
How to Apply a Function to Sliding Window Slices in Python
This Python code applies a given function to every contiguous window of a specified size in a list, returning a list of results.
def apply_to_sliding_windows(data, window_size, func):
return [func(data[i:i + window_size]) for i in range(len(data) - window_size + 1)]
if __name__ == "__main__":
numbers = [1, 2, 3, 4, 5, 6]
window_size = 3
results = apply_to_sliding_windows(numbers, window_size, sum)
print(results)
results…
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 Generate a Geometric Progression List in Python
This Python function builds a list of n terms in a geometric progression, starting with a given first term and multiplying by a constant ratio at each step.
def geometric_progression(first_term, ratio, count):
"""
Generate a list of 'count' terms in a geometric progression
starting with 'first_term' and multiplied by 'ratio' each step.
"""
progression = []
current = first_term
for _ in range(count):
progression.append(current)
c…
How to Replace Outliers Beyond Threshold with Cap in Python
Replace values that fall below a lower threshold or above an upper threshold by capping them to the threshold values using a simple Python function.
def replace_outliers_with_cap(data, lower_threshold=None, upper_threshold=None):
"""Replace values beyond given thresholds with the threshold values (capping)."""
if lower_threshold is None and upper_threshold is None:
raise ValueError("At least one threshold must be provided.")
capped_data = …
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}"…
Sort list by multiple keys with tuple ordering in Python
Sort a list of dictionaries by multiple criteria — surname, age, then score descending — using a tuple key and negation.
def sort_multi_key(data):
# Sorts by surname, then age, then score descending
return sorted(
data,
key=lambda person: (
person['surname'].lower(),
person['age'],
-person['score'] # negative to reverse sort by score
)
)
if __name__ == "__main__"…
Take While Predicate True From Start in Python
Create a custom take_while function that collects elements from an iterable until a predicate returns False, then stops.
def take_while(predicate, iterable):
"""Return elements from iterable until the predicate becomes False."""
result = []
for item in iterable:
if predicate(item):
result.append(item)
else:
break
return result
if __name__ == "__main__":
numbers = [2, 4, 6, 7,…
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.