Reference library

Python Code Samples

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

3 matches
Files & data easy

Parse Fixed Width Data File by Column Slices in Python

Extract fields from fixed-width text by slicing each line at defined column offsets, with a dictionary describing the boundaries.

fixed-width string-slicing parsing
Python
from pathlib import Path


def parse_fixed_width(data: str, slices: dict[str, tuple[int, int]]) -> list[dict[str, str]]:
    lines = data.strip().splitlines()
    records = []
    for line in lines:
        record = {}
        for name, (start, end) in slices.items():
            record[name] = line[start:end].strip()…
13 0 Open
Dictionaries & sets easy

How to Extract Data by Category in Python with Dictionaries and Sets

Use set comprehensions and a defaultdict to extract product names by category and compute total prices per category from a list of dictionaries.

dictionaries sets comprehensions
Python
from collections import defaultdict

# Sample data: products with categories and prices
product_data = [
    {"name": "Apple", "category": "fruit", "price": 0.50},
    {"name": "Banana", "category": "fruit", "price": 0.30},
    {"name": "Carrot", "category": "vegetable", "price": 0.80},
    {"name": "Bread", "category…
12 0 Open
Modern tooling easy

How to Parse and Extract Nested Data in Python

Load JSON files with Path and recursively extract values by key from nested Python structures using modern typing and standard library.

json pathlib recursion
Python
import json
from pathlib import Path
from typing import Any, Dict, List, Union

def load_data(filepath: Union[str, Path]) -> Union[Dict[str, Any], List[Any]]:
    """Load JSON data from a file with modern Path handling."""
    path = Path(filepath)
    if not path.exists():
        raise FileNotFoundError(f"File not f…
12 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.