Reference library

Python Code Samples

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

6 matches
Files & data easy

How to Convert CSV Column Types While Reading in Python

Read a CSV file and automatically convert column values to int, float, str, or bool based on type suffixes in the header names.

csv type-conversion file-io
Python
import csv
from pathlib import Path
from typing import Any

def read_csv_with_types(filepath: str) -> list[dict[str, Any]]:
    """Read CSV and convert column types based on header suffixes."""
    converters = {
        "int": int,
        "float": float,
        "str": str,
        "bool": lambda v: v.strip().lower(…
11 0 Open
Files & data easy

How to Parse Path Components with pathlib Path in Python

Parse a file path into parent directory, filename, stem, suffix, and parts using the standard library pathlib module.

pathlib filesystem file-paths
Python
from pathlib import Path

if __name__ == "__main__":
    p = Path("data/reports/2024/final.txt")
    print(f"Path: {p}")
    print(f"Parent: {p.parent}")
    print(f"Name: {p.name}")
    print(f"Stem: {p.stem}")
    print(f"Suffix: {p.suffix}")
    print(f"Parts: {p.parts}")
    print(f"Anchor: {p.anchor}")
    print(…
13 0 Open
Algorithms & data structures medium

Product of All Elements Except Self in Python

Given a list of integers, return a list where each element is the product of all other elements except itself, using prefix and suffix products in O(n) time and O(1) extra space.

array prefix suffix
Python
def product_except_self(nums):
    n = len(nums)
    result = [1] * n
    
    left_product = 1
    for i in range(n):
        result[i] = left_product
        left_product *= nums[i]
    
    right_product = 1
    for i in range(n - 1, -1, -1):
        result[i] *= right_product
        right_product *= nums[i]
    
…
14 0 Open
Algorithms & data structures medium

Product of Array Except Self in Python Without Division

Compute the product of all array elements except the current one in O(n) time using prefix and suffix products, without using division.

arrays prefix-product suffix-product
Python
from math import prod


def product_except_self(nums):
    n = len(nums)
    result = [1] * n
    left_product = 1
    for i in range(n):
        result[i] = left_product
        left_product *= nums[i]

    right_product = 1
    for i in range(n - 1, -1, -1):
        result[i] *= right_product
        right_product *…
14 0 Open
Git + Python easy

How to Generate Git LFS Extension Patterns in Python

This script builds mock Git LFS file patterns for common geospatial extensions and filters them based on compression suffixes.

git lfs geospatial
Python
import itertools
import re

LFS_EXTENSIONS = {".csv", ".geojson", ".tif", ".shp", ".gpkg"}

def build_mock_lfs_pattern(base_name="data_usgs_lidar"):
    patterns = []
    for ext in sorted(LFS_EXTENSIONS):
        for variant in (("", ".lz4"), (".compressed",), (".b", ".a"), ("_v1", ".zip")):
            full_pattern …
11 0 Open
ML engineering pipelines easy

How to Generate Experiment Tracking Run IDs in Python

Generate unique experiment run IDs with timestamps and random suffixes for tracking ML pipeline executions.

run-ids experiment-tracking ml-pipelines
Python
import random
import string
import time

def generate_run_id(prefix="exp"):
    timestamp = time.strftime("%Y%m%d_%H%M%S")
    suffix = "".join(random.choices(string.ascii_lowercase + string.digits, k=6))
    return f"{prefix}_{timestamp}_{suffix}"

if __name__ == "__main__":
    # Simulate tracking three experiment r…
13 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.