Reference library

Python Code Samples

Medium snippets you can copy, study, and run in the browser editor.

8 matches
Files & data medium

How to Build a CSV Comparison Tool That Highlights Every Changed Cell in Python

Read two CSV files with DictReader, compare cell by cell, and return a list of dictionaries describing each changed cell using only the standard library.

csv comparison diff
Python
import csv
from pathlib import Path

def csv_cell_diff(file_a: str, file_b: str) -> list[dict]:
    rows_a = list(csv.DictReader(Path(file_a).open('r', newline='')))
    rows_b = list(csv.DictReader(Path(file_b).open('r', newline='')))
    if not rows_a or not rows_b:
        return []
    columns = list(rows_a[0].key…
40 0 Open
Files & data medium

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.

hashlib sha256 file-hashing
Python
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…
13 0 Open
Automation & scripting medium

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.

github-api api comparison
Python
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(…
34 0 Open
Testing & modern typing medium

How to Compare Execution Speed Between Python Functions

Measure and compare the average execution time of multiple Python functions using a reusable benchmark helper with time.perf_counter.

performance benchmarking time
Python
import time
import random

def method_a(values):
    """Sort using built-in sorted."""
    return sorted(values)

def method_b(values):
    """Sort using list's sort method."""
    values_copy = values[:]
    values_copy.sort()
    return values_copy

def method_c(values):
    """Sort manually using bubble sort (slow,…
37 0 Open
API design & gRPC medium

How to Filter Query Parameters by Operator in Python

Parse a URL query string and keep only parameters with allowed comparison operators like eq, gt, and lt.

query-parsing url api
Python
from urllib.parse import urlparse, parse_qs

def filter_operators(query_string, allowed=("eq", "gt", "lt")):
    parsed = urlparse(query_string)
    params = parse_qs(parsed.query)
    filtered = {}
    for key, values in params.items():
        if "__" in key:
            field, op = key.rsplit("__", 1)
            i…
12 0 Open
Big data & Spark medium

Bloom Filter Join Mock in Python

A mock hash join that uses a Bloom filter to pre-filter one table before performing an exact match, reducing the number of comparisons in large dataset joins.

bloom filter join hashing
Python
import hashlib
import random
import string


class BloomFilter:
    def __init__(self, size: int = 200, num_hashes: int = 3):
        self.bits = [False] * size
        self.size = size
        self.num_hashes = num_hashes

    def _hashes(self, item: str):
        result = []
        for seed in range(self.num_hashes…
12 0 Open
ML engineering pipelines medium

How to Mock ROC AUC in Python

Compute ROC AUC from scratch in Python using pairwise comparisons between positive and negative score distributions, ideal for testing ML models without sklearn.

machine-learning model-evaluation auc
Python
import random
from math import comb


def mock_roc_auc(scores, labels):
    """Compute mock ROC AUC by simulating a classifier's score distribution."""
    random.seed(42)
    n = len(labels)
    pos_scores = [scores[i] for i in range(n) if labels[i] == 1]
    neg_scores = [scores[i] for i in range(n) if labels[i] == …
12 0 Open
Auth & security at scale medium

How to Hash Passwords and Authenticate Users in Python

A beginner-friendly dataclass-based design that hashes passwords with PBKDF2 and verifies them securely using constant-time comparisons.

security password hashing pbkdf2
Python
import hashlib
import hmac
import secrets
from dataclasses import dataclass
from typing import Optional


@dataclass
class User:
    id: int
    username: str
    password_hash: str
    salt: str


def hash_password(password: str) -> tuple[str, str]:
    salt = secrets.token_hex(16)
    password_hash = hashlib.pbkdf2_…
16 0 Open

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

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. 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.