Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
How to Use singledispatch for Type-Based Overloading in Python
This code demonstrates Python's functools.singledispatch decorator to create functions that behave differently based on the type of their first argument.
from functools import singledispatch
@singledispatch
def process(value):
return f"Unknown type: {type(value).__name__}"
@process.register(int)
def _(value):
return f"Integer: {value * 2}"
@process.register(str)
def _(value):
return f"String: {value.upper()}"
@process.register(list)
def _(value):
re…
Parse CSV Data with a Python Class
Encapsulate CSV file loading and column/row access methods in a reusable DataParser class for beginners.
class DataParser:
def __init__(self, file_path):
self.file_path = file_path
self.data = []
def load_data(self):
with open(self.file_path, 'r') as file:
for line in file:
row = line.strip().split(',')
self.data.append(row)
return self.…
Build a lazy generator to read file lines in Python
Create a generator function that yields file lines one at a time, avoiding loading the entire file into memory, and demonstrate its lazy processing.
def lazy_lines(filepath):
"""Yield lines from a file one at a time without loading the whole file into memory."""
with open(filepath, 'r', encoding='utf-8') as file:
for line in file:
yield line.rstrip('\n')
if __name__ == "__main__":
# Create a sample file to demonstrate
sample_c…
Memory efficient map over large file in Python
A generator-based streaming map that processes a large file line by line without loading the whole file into memory.
import sys
def process_lines(file_path):
"""Memory-efficient map over a large file: yields processed lines."""
with open(file_path, 'r') as f:
for line in f:
# Example mapping: strip whitespace and uppercase
yield line.strip().upper()
if __name__ == "__main__":
# Use a sma…
Upload Assets to GitHub Release with Python Mock
Simulates uploading binary and text assets to a GitHub release using a mock server, returning structured metadata for each upload.
import json
import os
import tempfile
from datetime import datetime
class ReleaseUploader:
"""Simulates uploading assets to a release with a mock server."""
def __init__(self, owner: str, repo: str, tag: str):
self.owner = owner
self.repo = repo
self.tag = tag
self.uploade…
How to Build a Simple ML Pipeline with ZenML in Python
Build a mock machine learning pipeline with ZenML steps for data loading, training, and evaluation, and run it to print the final accuracy.
from zenml import pipeline, step
@step
def load_data() -> dict:
"""Simulate loading data from a source."""
return {"accuracy": 0.0, "loss": 1.0}
@step
def train_model(data: dict) -> dict:
"""Simulate training a model."""
data["accuracy"] = 0.95
data["loss"] = 0.1
return data
@step
def eva…
How to Save and Load PyTorch Model State Dict in Python
This code demonstrates how to save a PyTorch model's state dict to a file and load it back into a new model instance, verifying weights match.
import torch
import torch.nn as nn
class SimpleNet(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(4, 8)
self.fc2 = nn.Linear(8, 2)
def forward(self, x):
x = torch.relu(self.fc1(x))
return self.fc2(x)
if __name__ == "__main__":
model = Simp…
Load CSV Training Data Without Pandas in Python
This code loads a CSV file into a list of dictionaries using only the standard library, ideal for small ML training data without heavy dependencies.
import csv
from pathlib import Path
def load_csv(path):
"""Load CSV file into list of dicts without pandas."""
rows = []
with open(path, newline='', encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
rows.append(dict(row))
return rows
if __name__ == "__m…
How to Batch Load JSON Data in Python for Database Optimization
This code parses JSON data into records and loads them in batches to simulate efficient database insertion, reducing load and improving performance.
import json
import time
def parse_and_load(data, batch_size=100):
"""
Parse JSON data and batch-load into a list of dicts.
Demonstrates batching for database efficiency.
"""
records = json.loads(data)
batches = []
for i in range(0, len(records), batch_size):
batch = records[i:i + …
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.