Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
Find Local Minima (Valleys) in a Numeric List in Python
This code finds indices of all local minima (valleys) in a numeric list, including edge cases, using a simple loop that compares each element with its neighbors.
def find_local_minima(numbers):
"""Find indices of local minima (valleys) in a numeric list.
A value is a local minimum if it's less than or equal to its neighbors.
Edge elements are considered minima if they're less than or equal to their single neighbor.
"""
if not numbers:
return []…
Find Minimum Value in a List in Python
This code defines a function that finds and returns the minimum value in a list of numbers, handling empty lists gracefully by returning None.
def find_minimum(numbers):
"""
Find and return the minimum value in a list of numbers.
Args:
numbers: List of numeric values
Returns:
The minimum value, or None if the list is empty
"""
if not numbers:
return None
min_value = numbers[0]
for num in n…
How to Build a Running Maximum List in Python
Compute a list where each element is the maximum of all numbers seen so far from an input list.
def running_maximum(numbers):
result = []
current_max = float('-inf')
for num in numbers:
if num > current_max:
current_max = num
result.append(current_max)
return result
if __name__ == "__main__":
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
max_list = running_maximum(number…
How to Compute Sliding Window Sum of Size k in Python
Compute the sum of every contiguous subarray of a fixed size k using an efficient O(n) sliding window technique.
def sliding_window_sum(nums, k):
"""Return a list of sums for each contiguous subarray of size k."""
if not nums or k <= 0 or k > len(nums):
return []
result = []
window_sum = sum(nums[:k])
result.append(window_sum)
for i in range(k, len(nums)):
window_sum += nums[i] -…
How to Find Local Maxima in a Python List
Return the indices of all local maxima in a numeric list, where a peak is an element greater than both its immediate neighbors.
def find_peaks(numbers):
"""
Return the indices of local maxima in a numeric list.
A local maximum is an element greater than both its neighbors.
"""
if len(numbers) < 3:
return []
peaks = []
for i in range(1, len(numbers) - 1):
if numbers[i] > numbers[i - 1] and number…
How to Find the Third Smallest Element in a Python List
Find the third smallest distinct value in a Python list by sorting unique elements and returning the third index.
def find_third_smallest(numbers):
if len(numbers) < 3:
return None
unique_sorted = sorted(set(numbers))
if len(unique_sorted) < 3:
return None
return unique_sorted[2]
if __name__ == "__main__":
sample = [5, 2, 8, 2, 9, 1, 7, 3]
result = find_third_smallest(sampl…
How to implement binary search in Python
Standalone binary search function that returns the index of a target in a sorted list, or -1 if not found.
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
if __name__ ==…
How to Merge Sorted Chunk Files in Python
Merge multiple sorted text files into one sorted output file using a heap for efficient k-way merging.
import heapq
def merge_sorted_chunks(chunks, output_path):
"""Merge multiple sorted iterables into single sorted output file."""
with open(output_path, "w") as out_f:
# Open all chunk files
handles = [open(chunk, "r") for chunk in chunks]
try:
# Heap of (value, index) tupl…
Implement the Strategy Pattern with Interchangeable Algorithm Classes in Python
Uses abstract base classes to define a SortStrategy interface, then swaps between BubbleSort and QuickSort at runtime.
from abc import ABC, abstractmethod
from typing import List
class SortStrategy(ABC):
@abstractmethod
def sort(self, data: List[int]) -> List[int]:
pass
class BubbleSort(SortStrategy):
def sort(self, data: List[int]) -> List[int]:
result = data[:]
n = len(result)
for i in…
Template Method Pattern in Python: Define Base Class with Algorithm Steps
Create a template method base class using ABC that defines the skeleton of an algorithm while letting subclasses implement specific steps.
from abc import ABC, abstractmethod
class DataProcessor(ABC):
"""Template method that defines the skeleton of an algorithm."""
def process(self):
"""Template method - defines the sequence of steps."""
self.load_data()
self.clean_data()
self.transform_data()
self.s…
Binary Search for Ship Capacity in Python
Use binary search to find the minimum ship capacity that can transport all packages within a given number of days.
def ship_within_days(weights, days):
def can_ship(capacity):
current = 0
needed_days = 1
for weight in weights:
if current + weight > capacity:
needed_days += 1
current = 0
current += weight
return needed_days <= days
low …
Binary Search on Answer in Python: Koko Eating Bananas
Find the minimum eating speed so Koko finishes all banana piles within a given hour limit using binary search on the answer.
import math
def min_eating_speed(piles, h):
"""Return minimum integer eating speed K so Koko finishes within h hours."""
def hours_needed(speed):
return sum(math.ceil(p / speed) for p in piles)
low, high = 1, max(piles)
while low < high:
mid = (low + high) // 2
if hours_needed…
Container With Most Water: Two-Pointer Solution in Python
Find the maximum water a container can hold from a list of heights using an efficient two-pointer technique in O(n) time.
from typing import List
def max_water_container(heights: List[int]) -> int:
left, right = 0, len(heights) - 1
max_area = 0
while left < right:
width = right - left
height = min(heights[left], heights[right])
area = width * height
max_area = max(max_area, area)
…
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 Elements Appearing More Than n/3 Times in Python
Return all elements that occur more than len(array)/3 times using a simple dictionary counter.
def majority_third(arr):
"""Return elements appearing more than len(arr)/3 times."""
cutoff = len(arr) / 3
counts = {}
for x in arr:
counts[x] = counts.get(x, 0) + 1
return [x for x, c in counts.items() if c > cutoff]
if __name__ == "__main__":
test1 = [3, 2, 3]
test2 = [1, 1, 1, …
Find Longest Consecutive Sequence in Python
Find the length of the longest consecutive elements sequence in an unsorted array using a set for O(n) lookups.
def longest_consecutive_length(nums):
num_set = set(nums)
longest = 0
for num in num_set:
if num - 1 not in num_set:
current = num
current_streak = 1
while current + 1 in num_set:
current += 1
current_streak += 1
…
Find Longest Increasing Subsequence Length in Python
Compute the length of the longest increasing subsequence in an array using dynamic programming.
def longest_increasing_subsequence(nums):
if not nums:
return 0
dp = [1] * len(nums)
for i in range(1, len(nums)):
for j in range(i):
if nums[i] > nums[j]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)
if __name__ == "__main__":
# Demo with…
Find Maximum Distance Between Identical Elements in Python
Compute the maximum index distance between any two identical elements in a list using a dictionary to track first occurrences.
from collections import defaultdict
def max_distance_between_identical(nums):
first_occurrence = {}
max_dist = 0
for i, num in enumerate(nums):
if num in first_occurrence:
dist = i - first_occurrence[num]
max_dist = max(max_dist, dist)
else:
first_occur…
Find Median of Two Sorted Arrays in Python
Merges two sorted arrays with a two-pointer walk and returns the median of the combined sorted sequence.
def median_of_two_sorted_arrays(nums1, nums2):
merged = []
i = j = 0
while i < len(nums1) and j < len(nums2):
if nums1[i] <= nums2[j]:
merged.append(nums1[i])
i += 1
else:
merged.append(nums2[j])
j += 1
merged.extend(nums1[i:])
merged.…
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}")
Find Missing Numbers, Duplicates, and Ranges in Python
Analyze a list to identify missing numbers, duplicate values, and contiguous ranges using sets and the Counter class.
def find_missing_duplicates_ranges(numbers):
"""Find missing numbers, duplicates, and ranges in a list."""
from collections import Counter
if not numbers:
return {"missing": [], "duplicates": [], "ranges": []}
full_range = set(range(min(numbers), max(numbers) + 1))
present = set(n…
Find Peak Element in Python Using Binary Search
A binary search solution that finds any peak element (an element strictly greater than its neighbors) in an unsorted array in O(log n) time.
def find_peak_element(nums):
left, right = 0, len(nums) - 1
while left < right:
mid = (left + right) // 2
if nums[mid] > nums[mid + 1]:
right = mid
else:
left = mid + 1
return left
if __name__ == "__main__":
test1 = [1, 2, 3, 1]
tes…
Find Pivot Index in Python
Locate the index where the sum of elements to the left equals the sum to the right, using a single pass with prefix sums.
def find_pivot_index(nums):
total = sum(nums)
left_sum = 0
for i, num in enumerate(nums):
if left_sum == total - left_sum - num:
return i
left_sum += num
return -1
if __name__ == "__main__":
test_cases = [
[1, 7, 3, 6, 5, 6],
[1, 2, 3],
[2, 1, -…
Find k Closest Points to Origin in Python
Sorts a list of (x, y) point tuples by their Euclidean distance from the origin and returns the k nearest points.
import math
def k_closest(points, k):
points.sort(key=lambda p: math.sqrt(p[0]**2 + p[1]**2))
return points[:k]
if __name__ == "__main__":
points = [(1, 2), (3, 4), (-1, 0), (5, 5), (0, 1)]
k = 3
result = k_closest(points, k)
print(f"Original points: {points}")
print(f"K closest points (k…
Browse by section
Each section groups closely related Python snippets.
Guide: free Python code samples library
Copy-ready Python snippets for learners and developers
PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.
How to use this library
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- Run it in the IDE, tweak values, then take a related quiz or tutorial lesson
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.