Python Code
Samples
Medium snippets you can copy, study, and run in the browser editor.
Product of All Elements Except Self in Python
Given a list of integers, return a list where each element is the product of all other elements except itself, using prefix and suffix products in O(n) time and O(1) extra space.
def product_except_self(nums):
n = len(nums)
result = [1] * n
left_product = 1
for i in range(n):
result[i] = left_product
left_product *= nums[i]
right_product = 1
for i in range(n - 1, -1, -1):
result[i] *= right_product
right_product *= nums[i]
…
Quickselect in Python: Find the kth Smallest Element
Python implementation of the Quickselect algorithm to find the kth smallest element in an unsorted list with average O(n) time complexity.
def quickselect(arr, k):
"""
Returns the k-th smallest element (0-indexed) using Quickselect.
Average: O(n), Worst: O(n^2)
"""
if len(arr) == 1:
return arr[0]
pivot = arr[-1]
left = [x for x in arr[:-1] if x <= pivot]
right = [x for x in arr[:-1] if x > pivot]
if k < len(l…
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] …
Find Dead Code in a Python Project Using AST
Walk a project tree, parse every Python file with ast, and list defined functions that are never called anywhere.
import ast
import os
import sys
def find_dead_code(project_path):
defined_functions = {}
called_functions = set()
for root, dirs, files in os.walk(project_path):
for file in files:
if file.endswith('.py'):
filepath = os.path.join(root, file)
with open(f…
Find Unused Python Packages Automatically
Scan a Python project's source files for imports and list installed packages not imported anywhere.
import pkg_resources
import ast
import os
import sys
from pathlib import Path
def find_imports_in_project(project_dir="."):
imports = set()
for py_file in Path(project_dir).rglob("*.py"):
try:
with open(py_file, "r") as f:
tree = ast.parse(f.read())
for node in …
Generate Holiday Calendars for Different Countries in Python
Generate a sorted list of public holidays for a given country and year using Python's calendar and datetime modules.
import calendar
from datetime import date, timedelta
def generate_holiday_calendar(country_code, year=2025):
holidays = []
if country_code == "US":
# New Year's Day
holidays.append(date(year, 1, 1))
# Independence Day
holidays.append(date(year, 7, 4))
# Thanksgivin…
How to Detect Applications Consuming Excessive Memory in Python
Use psutil to list the top memory-using processes by RSS and print their names, PIDs, and memory usage in MB.
import psutil
def find_top_memory_processes(limit=5):
"""Return top `limit` processes by memory usage (RSS)."""
processes = []
for proc in psutil.process_iter(['pid', 'name', 'memory_info']):
try:
info = proc.info
mem = info['memory_info'].rss if info['memory_info'] else 0…
How to Detect Recently Installed Software in Python
Uses subprocess to call pip and parse package metadata to list recently installed Python packages.
import subprocess
import sys
from datetime import datetime, timedelta
def detect_recently_installed(days=7):
"""Detect recently installed software packages."""
recent_packages = []
cutoff_date = datetime.now() - timedelta(days=days)
try:
# For pip-installed packages (Python packages)
…
How to Scan Open Ports on a Host with Python
A Python function that uses socket.connect_ex to check for open TCP ports on a given host within a range and returns a list of open ports.
import socket
def scan_ports(host, start_port, end_port):
open_ports = []
for port in range(start_port, end_port + 1):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.5)
result = sock.connect_ex((host, port))
if result == 0:
open_ports.app…
How to Validate SSL Certificates for Multiple Domains in Python
A Python utility that checks SSL certificate expiry dates for a list of domains using the standard library ssl and socket modules.
import ssl
import socket
from datetime import datetime
def check_ssl_certificate(hostname: str, port: int = 443) -> dict:
"""Validate SSL certificate for a given hostname."""
context = ssl.create_default_context()
with socket.create_connection((hostname, port), timeout=5) as sock:
with context.wra…
Pivot long to wide transformation dict
Transform a list of dictionaries from long format to wide format by pivoting on a key column and aggregating values, using pure Python.
def pivot_long_to_wide(rows, key_col, value_col, id_cols=None):
"""
Convert long-format data (list of dicts) to wide format.
Args:
rows: List of dicts in long format
key_col: Column name to pivot on (becomes new column headers)
value_col: Column name whose values become the cel…
Generate Release Notes Markdown from PR Titles in Python
Generate structured Markdown release notes from a list of pull request titles using conventional commit types.
import json
from datetime import datetime, timezone
PRS = [
{"title": "feat: add user login", "number": 12, "merged_at": "2025-01-10"},
{"title": "fix: resolve payment timeout", "number": 13, "merged_at": "2025-01-11"},
{"title": "chore: bump dependencies", "number": 14, "merged_at": "2025-01-12"},
{"…
How to generate and parse an interactive rebase TODO list in Python
Generate a Git interactive rebase TODO list from commit data and parse it back into structured records.
import re
from collections import namedtuple
Commit = namedtuple("Commit", ["hash", "subject"])
def generate_rebase_todo(commits, action="pick"):
todo_lines = []
for i, commit in enumerate(commits):
if i == 0 and action == "reword":
todo_lines.append(f"reword {commit.hash} {commit.subject…
Python Script to Rotate a Leaked API Key
A checklist-driven Python script that scans a codebase for a leaked API key, replaces it with a new one, and prints a step-by-step rotation checklist.
#!/usr/bin/env python3
"""Checklist for rotating a leaked API key across a codebase."""
import re
from pathlib import Path
CHECKLIST = [
"Identify all files containing the leaked key",
"Generate a new key with sufficient entropy",
"Update the secret storage/CI environment variables",
"Replace the ol…
Mock S3 List Objects Paginator in Python
This code implements a mock S3 paginator that yields pages of object keys, mimicking the behavior of boto3's list_objects_v2 paginator for local testing.
import json
from datetime import datetime, timezone
class MockS3Paginator:
"""A mock S3 list_objects_v2 paginator returning pages of keys."""
def __init__(self, bucket, all_keys, page_size=1000):
self.bucket = bucket
self.all_keys = all_keys
self.page_size = page_size
def pagina…
Benchmark list.append vs deque.append in Python
Measures and compares the performance of appending to a Python list versus a collections.deque using timeit.repeat, showing best and average timings.
"""Benchmark list.append vs collections.deque.append."""
import timeit
def bench(stmt, setup, repeat=5, number=1_000_000):
times = timeit.repeat(stmt, setup=setup, repeat=repeat, number=number)
return min(times), sum(times) / len(times)
if __name__ == "__main__":
number = 1_000_000
list_best, list_a…
How to Share Memory Between Processes in Python with multiprocessing.Value and Array
Share a numeric value and a list-like array across multiple Python processes using multiprocessing.Value and multiprocessing.Array, with each process modifying the same memory.
import multiprocessing
def worker(shared_value, shared_array, index):
shared_value.value += 10
shared_array[index] = shared_array[index] * 2
if __name__ == "__main__":
shared_value = multiprocessing.Value("i", 5)
shared_array = multiprocessing.Array("i", [1, 2, 3, 4, 5])
processes = []
for i…
How to Share a Dict and List Between Processes with multiprocessing Manager in Python
This code demonstrates how to share a dictionary and a list between multiple processes using multiprocessing.Manager, enabling safe concurrent updates.
import multiprocessing as mp
def worker(shared_dict, shared_list, name):
shared_dict[name] = name.upper()
shared_list.append(name)
print(f"{name} added to shared structures")
def main():
with mp.Manager() as manager:
shared_dict = manager.dict()
shared_list = manager.list()
…
Merge K Sorted Lists in Python with heapq
Merge k sorted lists into one sorted list in O(N log k) time using a min-heap of current elements.
import heapq
def merge_k_sorted_lists(lists):
heap = []
for i, lst in enumerate(lists):
if lst: # only push non-empty lists
heapq.heappush(heap, (lst[0], i, 0))
result = []
while heap:
val, list_idx, elem_idx = heapq.heappop(heap)
result.append(val)
if elem…
How to Flag Unexpected Diff Changes in Python
Compares two snapshot lists, detects unexpected differences, and returns a flag indicating whether the snapshot should be updated.
import difflib
def snapshot_diff(before, after, intentional_changes=None):
"""Compare snapshots and flag only unexpected differences."""
intentional_changes = intentional_changes or set()
diff = list(difflib.unified_diff(before, after, lineterm=""))
has_unexpected = False
for line in diff:
…
How to Use Hypothesis Strategies for Lists of Text in Python
Generate random lists of non-empty strings with Hypothesis and verify that joining them with a comma-and-space separator meets expected length and containment invariants.
from hypothesis import given, strategies as st
from hypothesis import example
@given(st.lists(st.text(min_size=1, max_size=10), min_size=1, max_size=5))
def test_joined_string_length(items):
"""Each text is non-empty; a joined string should be at least as long
as the number of items (separator adds character…
How to Validate Data in Python with Typing Hints
Build a runtime validation helper that checks values against Python type hints like Optional, list, and basic types.
from typing import Any, Optional, Union, TypeVar, get_origin, get_args
T = TypeVar("T")
def validate(value: Any, expected_type: type) -> Optional[str]:
"""Returns an error message if value doesn't match expected_type, else None."""
# Handle Optional[...] types
origin = get_origin(expected_type)
if or…
How to Mock a Kafka Rebalance Listener in Python
Simulate Kafka consumer rebalance callbacks (on_partitions_revoked and on_partitions_assigned) with a mock consumer to test listener logic.
import time
from collections import defaultdict
class MockKafkaConsumer:
def __init__(self):
self.assignments = defaultdict(list)
self.rebalances = 0
def assign(self, partitions):
self.rebalances += 1
self.assignments.clear()
for partition in partitions:
s…
How to Build a Bloom Filter to Reduce Cache Misses in Python
Implement a probabilistic Bloom filter in Python that lets a cache quickly determine which keys are definitely not present, reducing expensive source lookups on cache misses.
import hashlib
import random
class BloomFilter:
def __init__(self, size=100, num_hashes=3):
self.size = size
self.num_hashes = num_hashes
self.bit_array = [0] * size
def _hashes(self, item):
result = []
for i in range(self.num_hashes):
hash_value = int(hash…
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.