Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Compare Strings with casefold in Python
Compares two strings ignoring case differences using the casefold() method for proper Unicode normalization.
def compare_strings(str1: str, str2: str) -> bool:
return str1.casefold() == str2.casefold()
if __name__ == "__main__":
tests = [
("HELLO", "hello"),
("Straße", "STRASSE"),
("Python", "Python"),
("Mixed Case", "mixed case"),
]
for s1, s2 in tests:
print(f"{s1!r}…
Pairwise Adjacent Differences in a Python List
Computes the absolute differences between each pair of adjacent elements in a list using a concise list comprehension.
def adjacent_differences(nums):
"""Return list of absolute differences between adjacent elements."""
return [abs(nums[i] - nums[i + 1]) for i in range(len(nums) - 1)]
if __name__ == "__main__":
sample = [3, 7, 2, 9, 5]
diffs = adjacent_differences(sample)
print("Original list:", sample)
print…
Compare Two Folder Structures and Find Differences in Python
Walks two directories using os.walk, builds sets of relative paths, and prints items that exist in only one folder.
import os
def compare_folders(path1, path2):
"""
Compare the file/folder structure of two directories and print differences.
"""
def get_structure(root):
structure = set()
for dirpath, dirnames, filenames in os.walk(root):
rel_path = os.path.relpath(dirpath, root)
…
Compare Two Dictionaries in Python
Compare two dictionaries by finding common keys, unique keys, and value differences using Python's set operations.
def compare_data(dict1, dict2):
"""Compare two dictionaries and summarize similarities/differences."""
keys1 = set(dict1.keys())
keys2 = set(dict2.keys())
common_keys = keys1 & keys2
only_in_first = keys1 - keys2
only_in_second = keys2 - keys1
print(f"Common keys ({len(common_keys…
How to Subtract Counters in Python for Bag Differences
Use the Counter class's subtraction operator to compute bag differences, removing items and counts that appear in one multiset but not the other.
from collections import Counter
def subtract_counters(bag1, bag2):
"""Return the difference of two Counters (bag1 - bag2)."""
return bag1 - bag2
if __name__ == "__main__":
inventory = Counter(apples=10, bananas=5, oranges=3)
sold = Counter(apples=4, bananas=2, grapes=2)
remaining = subtract_count…
How to Compare Two GitHub Repositories and Highlight Differences in Python
Fetch metadata from two GitHub repositories using the GitHub API and compare key attributes like stars, forks, license, and language, printing any differences.
import requests
import json
from pathlib import Path
def fetch_repo_data(owner, repo_name):
"""Fetch repository metadata from GitHub API."""
url = f"https://api.github.com/repos/{owner}/{repo_name}"
response = requests.get(url)
response.raise_for_status()
return response.json()
def compare_repos(…
How to Compare Files and Show a Diff in Python
Compare two text files and print a unified diff using Python's difflib module to highlight differences.
import difflib
from pathlib import Path
def compare_files(expected_path: str, actual_path: str) -> str:
"""Compare two text files and return a unified diff."""
expected = Path(expected_path).read_text()
actual = Path(actual_path).read_text()
diff = difflib.unified_diff(
expected.splitlines(ke…
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:
…
Check Covariate Balance in Python
Compute standardized mean differences and KS tests to check covariate balance between treatment and control groups in Python.
import numpy as np
from scipy import stats
def balance_check(treatment, covariate):
"""Check covariate balance between treatment and control groups."""
treat_vals = covariate[treatment == 1]
control_vals = covariate[treatment == 0]
# Standardized mean difference
pooled_std = np.sqrt((np.var(t…
Difference in Differences Mock in Python
Generate mock panel data with a known treatment effect and compute a difference-in-differences estimate using group and period means.
import numpy as np
import pandas as pd
# Generate mock panel data: 2 groups (control=0, treatment=1) × 2 periods (pre=0, post=1)
rng = np.random.default_rng(42)
n_per_cell = 50
data = []
for group in [0, 1]:
for period in [0, 1]:
# True effect: treatment increases outcome by 5 in the post period
…
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.