Reference library

Python Code Samples

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

36 matches
Git + Python easy

Build a Simple Log Graph in Python

Create a basic one-dimensional bar chart from log lines by counting occurrences of leading numeric keys.

logging visualization graph
Python
import heapq


def log_graph(log_lines: list[str]) -> str:
    """Build a simple per-line, one-dimensional visual graph from log entries."""
    counts: dict[int, int] = {}
    for line in log_lines:
        tokens = line.split()
        if tokens:
            try:
                idx = int(tokens[0])
            exce…
16 0 Open
Concurrency & performance medium

How to Share Memory Between Processes in Python with multiprocessing.Value and Array

Share a numeric value and a list-like array across multiple Python processes using multiprocessing.Value and multiprocessing.Array, with each process modifying the same memory.

multiprocessing shared-memory concurrency
Python
import multiprocessing

def worker(shared_value, shared_array, index):
    shared_value.value += 10
    shared_array[index] = shared_array[index] * 2

if __name__ == "__main__":
    shared_value = multiprocessing.Value("i", 5)
    shared_array = multiprocessing.Array("i", [1, 2, 3, 4, 5])

    processes = []
    for i…
13 0 Open
Concurrency & performance easy

How to Use Array Typecodes for Compact Numeric Storage in Python

This code demonstrates how to use the `array` module with typecodes to store integers, floats, and bytes in a memory-efficient way compared to standard Python lists.

array memory performance
Python
from array import array

def demonstrate_array_types():
    # Compact integer arrays
    small_ints = array('i', [1, 2, 3, 4, 5])
    unsigned_ints = array('I', [10, 20, 30])
    
    # Floating point arrays
    floats = array('f', [1.5, 2.5, 3.5])
    doubles = array('d', [1.123456789, 2.987654321])
    
    # Charac…
15 0 Open
Testing & modern typing easy

How to Filter Data in Python with Type Hints

A reusable filter_data helper uses optional predicates and numeric bounds with modern Python type hints.

filtering type-hints generics
Python
from typing import Iterable, TypeVar, Callable, Any

T = TypeVar("T")

def filter_data(
    items: Iterable[T],
    predicate: Callable[[T], bool] | None = None,
    *,
    min_value: float | None = None,
    max_value: float | None = None,
) -> list[T]:
    """Filter items by predicate and/or numeric bounds."""
    r…
11 0 Open
Testing & modern typing easy

How to Write pytest Test Function Assert Equal in Python

Write three pytest test functions that assert the result of an add() function equals an expected numeric value.

pytest assert testing
Python
import pytest

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

def test_add_positive_numbers():
    assert add(2, 3) == 5

def test_add_negative_numbers():
    assert add(-1, -2) == -3

def test_add_mixed_numbers():
    assert add(5, -3) == 2

if __name__ == "__main__":
    pytest.main([__file__, "-v"])
12 0 Open
API design & gRPC easy

Return Proper HTTP Status Codes Table in Python

Mock HTTP status code table with proper numeric and textual representations, including formatted status lines and a filtered table view.

http-status api mock
Python
# Mock HTTP status code table with proper numeric and textual representations

codes = {
    200: "OK",
    201: "Created",
    204: "No Content",
    301: "Moved Permanently",
    302: "Found",
    304: "Not Modified",
    400: "Bad Request",
    401: "Unauthorized",
    403: "Forbidden",
    404: "Not Found",
    50…
13 0 Open
ML engineering pipelines medium

How to Build an sklearn Pipeline with ColumnTransformer in Python

A mock example showing how to chain preprocessing and a regression model into a single sklearn Pipeline, scaling numeric features and one-hot encoding categorical features with ColumnTransformer.

sklearn pipeline columntransformer
Python
import numpy as np
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LinearRegression

# Mock dataset
X = np.array([[1, 'red'], [2, 'blue'], [3, 'red'], [4, 'green'], [5, 'blue']], dtype=o…
13 0 Open
ML engineering pipelines easy

How to ordinal encode categorical data in Python with sklearn

Convert job title categories into ordinal numeric labels using sklearn's OrdinalEncoder with explicit ordering.

ordinal-encoding sklearn categorical-data
Python
from sklearn.preprocessing import OrdinalEncoder
import numpy as np

# Mock data: small job title categories with known ordering
data = np.array([
    ["intern"],
    ["junior"],
    ["mid"],
    ["senior"],
    ["lead"]
])

# Define the ordinal order (lowest to highest)
categories = [["intern", "junior", "mid", "seni…
15 0 Open
ML engineering pipelines easy

One Hot Encode Categories in Python

Convert a list of categorical strings into one-hot encoded numeric vectors using pure Python and NumPy.

one-hot encoding categorical numpy
Python
import numpy as np

categories = ["red", "green", "blue", "red", "blue", "green", "red"]

unique = sorted(set(categories))
lookup = {cat: i for i, cat in enumerate(unique)}

one_hot = []
for cat in categories:
    row = [0] * len(unique)
    row[lookup[cat]] = 1
    one_hot.append(row)

print("Categories:", categories…
13 0 Open
A/B testing & experimentation easy

How to Calculate Secondary Metrics in Python

Computes distribution, variability, and spread of a numeric dataset using Python's statistics and collections modules.

statistics data-analysis metrics
Python
import random
import statistics
from collections import Counter

def explore_secondary_metrics(data):
    """Calculate secondary metrics: distribution, variability, and spread."""
    if not data:
        return "No data provided"
    
    total = sum(data)
    mean = statistics.mean(data)
    median = statistics.medi…
16 0 Open
Database scaling & optimization easy

How to Convert Data with Scaling for Database Optimization in Python

A beginner-friendly helper that normalizes and scales numeric fields in a list of dicts, reducing storage footprint for database efficiency.

data conversion database scaling
Python
import json
from datetime import datetime

def convert_data(data: list[dict], scale_factor: int = 1) -> list[dict]:
    """Convert a list of dicts to a scaled, normalized format for database efficiency."""
    converted = []
    for row in data:
        normalized = {}
        for key, value in row.items():
          …
14 0 Open
Database scaling & optimization easy

How to Limit a Result Set to Top N Rows in Python

Sort a list of dictionaries by a numeric key and return only the top N results, formatted as a readable ranked list.

sorting slicing top-n
Python
import random

def top_n_mock(limit: int = 5):
    """Return a formatted top-N result set as a mock example."""
    # Simulated data source
    scores = [
        {"name": "Alice", "score": 87},
        {"name": "Bob", "score": 92},
        {"name": "Charlie", "score": 78},
        {"name": "Diana", "score": 95},
    …
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.