Python Code
Samples
Medium snippets you can copy, study, and run in the browser editor.
How to Find the Previous Smaller Element in Python
Use a monotonic stack to find the nearest smaller element to the left of each item in a list, returning -1 when none exists.
from collections import deque
def previous_smaller_elements(arr):
stack = deque()
result = [-1] * len(arr)
for i in range(len(arr)):
while stack and arr[stack[-1]] >= arr[i]:
stack.pop()
if stack:
result[i] = arr[stack[-1]]
stack.append(i)
return resul…
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 []
…
How to Generate a Power Set in Python with Bitmasks
Generate the power set of a small list using a bitmask approach, producing all possible subsets.
def power_set(items):
"""Generate the power set of a list using bitmask approach."""
n = len(items)
result = []
for mask in range(1 << n):
subset = []
for i in range(n):
if mask & (1 << i):
subset.append(items[i])
result.append(subset)
r…
Merge k sorted lists in Python using a heap
Merge k individually sorted lists into one sorted list in Python using a min-heap.
import heapq
def merge_k_sorted_lists(lists):
heap = []
# Push the first element of each list onto the heap
for i, lst in enumerate(lists):
if lst:
heapq.heappush(heap, (lst[0], i, 0))
result = []
while heap:
val, list_idx, elem_idx = heapq.heappop(heap)
re…
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]
…
Product of Array Except Self in Python Without Division
Compute the product of all array elements except the current one in O(n) time using prefix and suffix products, without using division.
from math import prod
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 *…
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] …
How to stream parse JSON arrays in Python
This code demonstrates two generators: one that streams a JSON array as individual chunks, and another that incrementally parses those chunks into Python objects using json.JSONDecoder.
import json
def json_array_stream(items):
"""Generator that yields JSON-encoded values one at a time."""
yield "["
for i, item in enumerate(items):
if i > 0:
yield ","
yield json.dumps(item)
yield "]"
def parse_json_stream(stream):
"""Consumes a stream of JSON fragme…
Circuit Breaker Pattern in Python for LLM API Calls
Implements a circuit breaker class that wraps LLM client calls to fail fast when the service is degrading, then recover automatically after a timeout.
import time
class CircuitBreaker:
def __init__(self, failure_threshold=3, recovery_timeout=5):
self.failure_threshold = failure_threshold
self.recovery_timeout = recovery_timeout
self.failure_count = 0
self.state = "closed"
self.last_failure_time = None
def call(self, …
How to Repair Malformed JSON Braces Heuristically in Python
Heuristically fix malformed JSON by balancing braces and quotes, using a stack-based approach to add missing closing characters.
import json
import re
def repair_json(text: str) -> str:
"""Heuristically repair malformed JSON by balancing braces and quotes."""
# Trim whitespace and handle leading/trailing garbage
text = text.strip()
# Remove common non-JSON decorations
text = re.sub(r'^(
How to Retry LLM Calls on Rate Limit Errors in Python
Implement a retry mechanism with exponential backoff for LLM API calls that raises a custom RateLimitError, using a mock function to demonstrate the pattern.
import time
import random
def mock_llm_call():
"""Simulates an LLM API call that may raise a rate limit error."""
if random.random() < 0.4: # 40% chance of rate limit
raise RateLimitError("Rate limit exceeded. Try again later.")
return {"response": "Hello world from mock LLM"}
class RateLimitE…
How to cache embeddings with a Python dict to avoid recomputation
Caches embeddings computed from text in a dictionary keyed by SHA-256 hash, returning cached results for repeated calls.
import hashlib
import time
class EmbeddingCache:
def __init__(self):
self.cache = {}
def _hash_text(self, text):
return hashlib.sha256(text.encode()).hexdigest()
def get_embedding(self, text, compute_func):
key = self._hash_text(text)
if key not in self.cache:
…
How to implement exponential backoff for LLM API calls in Python
A decorator that retries flaky LLM API calls with exponential delay, using a mock client to demonstrate the pattern.
import time
import random
class MockLLM:
def call(self, prompt):
if random.random() < 0.7: # 70% chance of transient failure
raise ConnectionError("API unavailable")
return f"LLM response for: {prompt}"
def with_exponential_backoff(max_retries=5, base_delay=0.1):
def decorator(fu…
How to parallel map embeddings with a thread pool in Python
Run embedding computations in parallel using ThreadPoolExecutor, collect results into a dict keyed by the original item.
import threading
from concurrent.futures import ThreadPoolExecutor
import time
def compute_embedding(item: int) -> tuple[int, int]:
time.sleep(0.05) # Simulate embedding work
return item, item * 10
def parallel_map_embed(items, max_workers=3):
results = {}
with ThreadPoolExecutor(max_workers=max_w…
Automatically Clean Temporary Files from Applications Using Python
A Python script that safely deletes temporary files from common application temp directories across Windows, Linux, and macOS, tracking cleaned count and disk space.
import os
import shutil
import tempfile
import platform
def clean_application_temp_files():
"""Delete common temporary file locations safely."""
system = platform.system()
temp_dirs = []
if system == "Windows":
temp_dirs.extend([
os.path.join(os.getenv("LOCALAPPDATA"), "Temp"),
…
Automatically Download the Latest Software Release from GitHub with Python
Use the GitHub API to fetch the latest release metadata and download the first asset (binary or archive) to a local directory.
import requests
import sys
from pathlib import Path
def download_latest_release(owner: str, repo: str, output_dir: str = ".") -> None:
"""Download the latest release asset from a GitHub repository."""
url = f"https://api.github.com/repos/{owner}/{repo}/releases/latest"
response = requests.get(url)
res…
Automatically Generate Charts from CSV Files with One Command
Read a CSV file with headers, extract the first two numeric columns, and save a matplotlib line chart as a PNG image.
import csv
import sys
from pathlib import Path
import matplotlib.pyplot as plt
def generate_chart(csv_path: str) -> None:
"""Read a CSV file with headers and plot the first two numeric columns."""
data = []
with open(csv_path, 'r', newline='') as f:
reader = csv.reader(f)
headers = next(re…
Build a Python Tool to Find All API Endpoints on a Website
A Python script that crawls a website, searches for common API endpoint patterns in HTML and JavaScript, and returns all discovered public API URLs.
import re
import requests
from urllib.parse import urljoin, urlparse
from collections import deque
def find_api_endpoints(base_url, max_pages=10):
visited = set()
queue = deque([base_url])
api_endpoints = set()
api_patterns = [
r'/api/[a-zA-Z0-9_/-]+',
r'/v[0-9]+/[a-zA-Z0-9_/-]+',…
Build a Python Utility That Verifies Backup Integrity Automatically
Automatically compute and verify SHA-256 checksums of backup files using a JSON manifest to detect missing or corrupted data.
import hashlib
import os
import json
def compute_checksum(filepath, algorithm='sha256'):
"""Compute checksum for the given file."""
hash_func = hashlib.new(algorithm)
with open(filepath, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b''):
hash_func.update(chunk)
return hash_f…
Create a Python Script That Detects Website Technology Stack Automatically
This script sends an HTTP request to a URL and inspects headers and HTML content to identify technologies like servers, frameworks, and JavaScript libraries.
import requests
from re import search
def detect_tech_stack(url):
tech_stack = []
try:
response = requests.get(url, timeout=5, headers={'User-Agent': 'Mozilla/5.0'})
headers = response.headers
html = response.text.lower() if response.text else ''
# Check server header
…
Detect Circular Imports Across Python Projects Automatically
This script walks through all .py files in a directory, builds an import graph, and uses depth-first search to find cycles—printing each circular dependency chain.
import ast
import sys
from pathlib import Path
from collections import defaultdict, deque
def find_imports(filepath):
"""Return set of module names imported by a Python file."""
imports = set()
try:
with open(filepath) as f:
tree = ast.parse(f.read())
except (SyntaxError, UnicodeDe…
Detect and Remove Blurry Images in Python with OpenCV
Automatically scan a directory of images, detect blur using Laplacian variance, and remove blurry images with a dry-run option for safety.
from pathlib import Path
import cv2
import numpy as np
def is_blurry(image_path, threshold=100.0):
"""
Detect if an image is blurry using Laplacian variance.
Returns True if blurry, False otherwise.
"""
img = cv2.imread(str(image_path), cv2.IMREAD_GRAYSCALE)
if img is None:
return True…
Discover RSS Feeds From Any Website in Python
Scrape a website's HTML to automatically find all linked RSS or Atom feed URLs using requests, BeautifulSoup, and regex.
import requests
import re
from urllib.parse import urljoin, urlparse
from bs4 import BeautifulSoup
def discover_rss_feeds(url):
"""Discover all RSS/Atom feeds linked from a given website."""
try:
headers = {'User-Agent': 'Mozilla/5.0 (compatible; RSSDiscovery/1.0)'}
response = requests.get(url…
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.