Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

12 matches
Dictionaries & sets easy

How to Count Co-occurrence Pairs in Python with Nested Dictionaries

This code counts how often any two items appear together in the same group, using a nested defaultdict keyed by item pairs.

dictionaries co-occurrence counter
Python
from itertools import combinations
from collections import defaultdict

def count_cooccurrences(items_per_group):
    cooccurrence = defaultdict(lambda: defaultdict(int))
    for group in items_per_group:
        for a, b in combinations(sorted(group), 2):
            cooccurrence[a][b] += 1
            cooccurrence[b…
12 0 Open
Algorithms & data structures easy

How to Compute the Cartesian Product of Two Lists in Python

Generates all ordered pairs from two lists using itertools.product and prints each combination.

itertools cartesian-product combinations
Python
from itertools import product

# Two small input lists
list_a = [1, 2, 3]
list_b = ["x", "y"]

# Compute the Cartesian product
result = list(product(list_a, list_b))

# Display the result
print("Cartesian product of", list_a, "and", list_b, "is:")
for pair in result:
    print(pair)
15 0 Open
Algorithms & data structures easy

How to Generate Permutations of Length r in Python

Generate and print all r-length permutations of a list using Python's itertools.permutations.

permutations itertools combinations
Python
from itertools import permutations

def show_permutations(items, r):
    result = list(permutations(items, r))
    for perm in result:
        print(perm)
    print(f"Total: {len(result)}")

if __name__ == "__main__":
    data = ["A", "B", "C"]
    show_permutations(data, 2)
15 0 Open
Algorithms & data structures easy

How to Get All Combinations of a List in Python

Generate and display all combinations of a given length from a list using Python's itertools.combinations.

itertools combinations list
Python
from itertools import combinations

def list_combinations(items, r):
    """Return all combinations of length r from a list."""
    return list(combinations(items, r))

if __name__ == "__main__":
    fruits = ["apple", "banana", "cherry", "date"]
    pick = 2
    result = list_combinations(fruits, pick)
    
    print…
12 0 Open
Comprehensions & generators easy

How to Generate Cartesian Product Combinations in Python

Use itertools.product to generate every combination across multiple iterables, a pattern common for product variant generation.

itertools cartesian product combinations
Python
from itertools import product

def generate_cartesian_combinations(*iterables):
    """Generate all Cartesian product combinations of given iterables."""
    return list(product(*iterables))

if __name__ == "__main__":
    colors = ["red", "green", "blue"]
    sizes = ["S", "M", "L"]
    styles = ["t-shirt", "hoodie"]…
13 0 Open
Comprehensions & generators easy

How to Generate Combinations with Replacement in Python

Generate all r-length combinations with repetition from a list using the standard library itertools.combinations_with_replacement function.

itertools combinations generator
Python
from itertools import combinations_with_replacement

items = ['A', 'B', 'C']
r = 2

combos = list(combinations_with_replacement(items, r))

for combo in combos:
    print(combo)

if __name__ == "__main__":
    print(f"Total combinations with replacement: {len(combos)}")
11 0 Open
Comprehensions & generators easy

How to generate combinations in Python with itertools

Generate all unique combinations of r items from a given list using itertools.combinations.

itertools combinations generators
Python
import itertools

def combinations_generator(items, r):
    return list(itertools.combinations(items, r))

if __name__ == "__main__":
    items = ['A', 'B', 'C', 'D']
    r = 2
    result = combinations_generator(items, r)
    for combo in result:
        print(combo)
    print(f"Total: {len(result)} combinations of {…
14 0 Open
Data pipelines & processing medium

How to Validate Fact Table Grain Row Counts in Python

Validate fact table grain by checking dimension key references, unique grain combinations, duplicate rows, and dimension cardinality from a CSV file.

csv data validation etl
Python
import csv
import hashlib
from pathlib import Path


def validate_fact_grain(fact_file: Path, expected_dim_keys: dict[str, set[str]]) -> dict:
    """
    Validate fact table grain by checking each row's dimension keys exist
    in expected dimension tables and row count consistency.
    """
    dim_references = {}
  …
13 0 Open
Testing & modern typing easy

How to Parametrize pytest Tests with Multiple Input Cases in Python

This code shows how to use pytest's @pytest.mark.parametrize decorator to run the same test function across multiple input-output combinations, checking that an add function behaves correctly for each case.

pytest parametrize testing
Python
import pytest

def add(a, b):
    return a + b


@pytest.mark.parametrize("a,b,expected", [
    (1, 2, 3),
    (5, 5, 10),
    (-1, 1, 0),
    (0, 0, 0),
    (10, -3, 7),
])
def test_add(a, b, expected):
    assert add(a, b) == expected


if __name__ == "__main__":
    pytest.main([__file__, "-v"])
14 0 Open
ML engineering pipelines easy

Grid Search Hyperparameters in Python

Perform exhaustive grid search over hyperparameter combinations using itertools.product and a scoring function.

grid-search hyperparameters itertools
Python
import itertools

def grid_search(param_grid, score_fn):
    """Perform exhaustive grid search over hyperparameter combinations."""
    keys = param_grid.keys()
    names = list(keys)
    values = [param_grid[name] for name in names]
    results = []

    for combination in itertools.product(*values):
        params =…
14 0 Open
ML engineering pipelines easy

How to Do Random Search for Hyperparameter Tuning in Python

A mock random search that samples hyperparameter combinations from a grid and ranks them by a dummy score, with a reproducible seed.

hyperparameter random-search ml
Python
import random

# Mock random search over a small hyperparameter grid
param_grid = {
    "learning_rate": [0.001, 0.01, 0.1],
    "batch_size": [16, 32, 64],
    "num_layers": [1, 2, 3]
}

def random_search(grid, n_iter=5, seed=42):
    """Perform random search over a hyperparameter grid."""
    random.seed(seed)
    k…
13 0 Open
A/B testing & experimentation medium

How to Generate an Orthogonal Array for A/B Testing in Python

Generate a mock orthogonal array for multi-layer experiments with NumPy, ensuring balanced level combinations across experiment groups.

ab-testing orthogonal-array numpy
Python
import numpy as np

def orthogonal_mock_layers(n_experiments: int, n_layers: int, n_levels: int) -> np.ndarray:
    """Generate an orthogonal array for multi-layer experiment design using base-level logic."""
    ortho = np.indices((n_levels,) * n_layers).reshape(n_layers, -1).T
    ortho = ortho % n_levels  # Classic…
14 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.