Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Compare Two Files by Content Hash Equality in Python
Compares two files by hashing their contents with SHA-256, skipping the hash if file sizes differ, and returns whether they are identical.
import hashlib
from pathlib import Path
def file_hash(path: Path, chunk_size: int = 8192) -> str:
sha256 = hashlib.sha256()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(chunk_size), b""):
sha256.update(chunk)
return sha256.hexdigest()
def files_are_identical(file_a: Pat…
How to Find HTML Elements by Tag, Class, ID, CSS Selector, and Attribute in BeautifulSoup
Parse an HTML string with BeautifulSoup and demonstrate five distinct ways to locate elements: by tag name, by class, by ID, by CSS selector, and by attribute.
from bs4 import BeautifulSoup
html_content = """
<html><body>
<h1 id="title" class="heading">Hello World</h1>
<p class="content">First paragraph</p>
<p class="content special">Second paragraph</p>
<a href="https://example.com" class="link">Click here</a>
<div id="footer">
<p>© 2024</p>
…
How to Group Files by Extension in Python
Group file names by their file extension using a dictionary and pathlib, producing a simple clear mapping for beginners.
from pathlib import Path
def group_data_by_extension(files: list[Path]) -> dict[str, list[str]]:
"""Group file names by their extension."""
grouped: dict[str, list[str]] = {}
for file in files:
ext = file.suffix.lower()
grouped.setdefault(ext, []).append(file.name)
return grouped
if…
How to Handle Missing Values in a CSV Numeric Column in Python
Clean missing entries in a CSV numeric column by filling them with the mean, median, a custom value, or dropping rows.
import csv
from pathlib import Path
import statistics
def clean_csv_numeric(input_path: str, output_path: str, column: str, strategy: str = "mean") -> None:
"""
Handles missing values in a numeric column of a CSV file.
Strategies: 'mean', 'median', 'drop', or 'fill' with a specified value.
"""
row…
How to Load a YAML Subset in Python Without PyYAML
Parse a flat, key-value YAML file with the Python standard library (re and pathlib), handling comments, quotes, and inline comments while skipping nested structures.
import re
from pathlib import Path
def load_yaml_subset(path):
"""Load a flat YAML file (key: value) without external dependencies."""
data = {}
with open(path, 'r', encoding='utf-8') as f:
for line in f:
# Skip empty lines and comments
line = line.strip()
if no…
How to Scrape Headlines from a News Website Using Beautiful Soup in Python
Scrape headline text from a news website using requests and Beautiful Soup with a CSS selector.
import requests
from bs4 import BeautifulSoup
def scrape_headlines(url: str, selector: str) -> list:
"""
Scrape headlines from a news website using Beautiful Soup.
Args:
url: The URL of the news website.
selector: CSS selector for headline elements.
Returns:
List of h…
How to Split Files by Extension in Python
Group files in a folder by their file extension into a dictionary using pathlib.
from pathlib import Path
def split_files_by_extension(folder_path):
folder = Path(folder_path)
files_by_ext = {}
for file_path in folder.iterdir():
if file_path.is_file():
ext = file_path.suffix.lower() or "no_extension"
files_by_ext.setdefault(ext, []).append(file_path.na…
How to Strip BOM When Reading UTF-8 Files in Python
Read a UTF-8 text file with Python's pathlib while automatically stripping the Byte Order Mark (BOM) so the first character isn't a hidden glyph.
from pathlib import Path
def read_text_without_bom(file_path):
"""Read a UTF-8 text file, stripping the BOM if present."""
return Path(file_path).read_text(encoding='utf-8-sig')
if __name__ == "__main__":
# Create a sample file with BOM for demonstration
sample_path = Path("sample_with_bom.txt")
…
Rotate Log Files in Python by Size
This code rotates a log file when its size exceeds a threshold, keeping a specified number of backups.
import os
import glob
from pathlib import Path
def rotate_log(log_path, max_size_bytes=1024, max_backups=3):
log_file = Path(log_path)
if log_file.stat().st_size <= max_size_bytes:
print(f"Log size {log_file.stat().st_size} bytes <= threshold, no rotation")
return
for i in range(max_backu…
Scrape HTML Tables and Convert Them to CSV Using Beautiful Soup in Python
Scrape a Wikipedia table with Beautiful Soup and write the data to a CSV file using the csv module.
import requests
from bs4 import BeautifulSoup
import csv
url = "https://en.wikipedia.org/wiki/List_of_countries_by_GDP_(nominal)"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
tables = soup.find_all('table', {'class': 'wikitable'})
if tables:
target_table = tables[2]
rows =…
Sync only changed files between two folders in Python
This code compares two folders and copies only the new or modified files from source to destination, skipping unchanged ones by comparing SHA-256 hashes.
import hashlib
from pathlib import Path
import shutil
def file_hash(path: Path, chunk_size: int = 8192) -> str:
hasher = hashlib.sha256()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(chunk_size), b""):
hasher.update(chunk)
return hasher.hexdigest()
def sync_files(src: s…
Build adjacency dict graph from edges in Python
Convert a list of edges into an undirected adjacency dictionary, mapping each node to its neighbors, with sorted output.
def build_adjacency_dict(edges):
graph = {}
for u, v in edges:
if u not in graph:
graph[u] = []
if v not in graph:
graph[v] = []
graph[u].append(v)
graph[v].append(u)
return graph
if __name__ == "__main__":
edges = [(1, 2), (2, 3), (3, 4), (4, 1)…
Check Invertible Mapping for Duplicate Values in Python
Detect duplicate values among (key, value) pairs to ensure the mapping is invertible, using a dictionary for O(1) lookups.
def invertible_after_dedup(pairs):
"""
Check whether a set of (key, value) pairs is invertible,
i.e., no duplicate values exist for different keys.
"""
seen = {}
for key, value in pairs:
if value in seen and seen[value] != key:
return False, f"Duplicate value '{value}' for k…
Group Data by Key in Python with Dictionaries and Sets
Group items into a dictionary of sets using a key function, a beginner-friendly pattern for organizing data by categories.
def group_data(items, key_func):
"""Group items into a dictionary of sets based on a key function."""
grouped = {}
for item in items:
key = key_func(item)
if key not in grouped:
grouped[key] = set()
grouped[key].add(item)
return grouped
if __name__ == "__main__":
…
How to Group Data by Category in Python with a Split Data Helper
This code groups a list of (category, item) pairs into a dictionary where each key is a category and each value is a list of items belonging to that category.
def split_data(categories):
"""
Group data items into buckets based on a key function.
Returns a dict where keys are bucket names and values are lists of items.
"""
buckets = {}
for category, item in categories:
if category not in buckets:
buckets[category] = []
buck…
How to Group a List of Dictionaries by Key in Python
Group a list of dictionaries by a specified key field using dict.setdefault to build a dictionary of lists.
def group_by_key(records, key):
grouped = {}
for record in records:
grouped.setdefault(record[key], []).append(record)
return grouped
if __name__ == "__main__":
data = [
{"name": "Alice", "dept": "engineering"},
{"name": "Bob", "dept": "sales"},
{"name": "Carol", "dept"…
How to Map Dictionary Values with a Transformation Function in Python
Create a reusable function that applies a transformation to every value in a dictionary and returns a new dict.
def transform_dict_values(d, func):
"""Apply a transformation function to every value in a dictionary."""
return {key: func(value) for key, value in d.items()}
if __name__ == "__main__":
original = {"a": 1, "b": 2, "c": 3}
doubled = transform_dict_values(original, lambda x: x * 2)
print(doubled)
…
How to Normalize Data in Python with Dictionaries and Sets
Normalize a list of dicts by keeping selected keys, stripping/lowercasing strings, and extracting unique sorted values using set comprehension.
def normalize_data(data, keys):
"""
Normalize a list of dictionaries by keeping only specified keys
and converting values to proper types.
"""
normalized = []
for item in data:
clean_item = {}
for key in keys:
value = item.get(key)
if isinstance(value, st…
How to Parse Data Into Dictionaries and Sets in Python
Parses raw student strings into a dictionary of lists and finds unique courses using a set.
from collections import defaultdict
def parse_students(raw_data):
"""Parse raw student strings into a dictionary of lists."""
parsed = defaultdict(list)
for entry in raw_data:
name, _, course = entry.partition(":")
parsed[course.strip()].append(name.strip())
return dict(parsed)
def fi…
How to Parse Query String to Dict with Duplicate Keys in Python
Convert a URL query string into a Python dictionary, merging duplicate keys into lists while keeping single values as scalars.
from urllib.parse import parse_qs
def parse_query_to_dict(query_string):
parsed = parse_qs(query_string, keep_blank_values=True)
return {key: values if len(values) > 1 else values[0] for key, values in parsed.items()}
if __name__ == "__main__":
query = "name=John&name=Jane&age=30&city=&city=Paris&empty…
How to Use MappingProxyType to Create Immutable Dict Views in Python
Create a read-only, immutable view of a dictionary using MappingProxyType from the types module, while the original dict stays mutable.
from types import MappingProxyType
config = {"debug": True, "port": 8080}
# Create an immutable read-only view of the dict
read_only_config = MappingProxyType(config)
print(f"Read-only value: {read_only_config['debug']}")
print(f"Dict is mapping: {isinstance(read_only_config, dict)}")
# Original dict can still be …
How to Use defaultdict(list) to Group Words by First Letter in Python
This code groups a list of words by their first letter using a defaultdict with a list factory, then prints each group sorted by initial.
from collections import defaultdict
def group_by_initial(words):
groups = defaultdict(list)
for word in words:
groups[word[0].upper()].append(word)
return dict(groups)
if __name__ == "__main__":
words = ["apple", "banana", "apricot", "blueberry", "cherry"]
result = group_by_initial(words)…
How to Use defaultdict(set) in Python to Group Unique Values
Group key-value pairs into a dictionary of sets, automatically creating a new set for each key using defaultdict.
from collections import defaultdict
def track_groups(pairs):
groups = defaultdict(set)
for key, value in pairs:
groups[key].add(value)
return groups
if __name__ == "__main__":
data = [
("fruit", "apple"),
("fruit", "banana"),
("fruit", "apple"),
("veg", "carrot…
Composition over Inheritance: How to Build a Wallet Account in Python
Demonstrates composition by wrapping a WalletAccount class in an AuditedWallet decorator-like class to add behavior without changing the original class.
class WalletAccount:
def __init__(self, owner, balance=0.0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("Deposit must be positive")
self.balance += amount
return self.balance
def withdraw(self, …
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.