Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
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.
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()…
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.
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…
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.
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…
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
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- 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.