Reference library

Python Code Samples

Easy snippets you can copy, study, and run in the browser editor.

15 matches
Lists & loops easy

Compare Two Lists in Python: Common, Only in First, Only in Second

A beginner-friendly helper that loops over two lists and returns items common to both, items only in the first list, and items only in the second list.

lists comparison loops
Python
def compare_lists(list1, list2):
    common = []
    only_in_first = []
    only_in_second = []
    
    for item in list1:
        if item in list2:
            common.append(item)
        else:
            only_in_first.append(item)
    
    for item in list2:
        if item not in list1:
            only_in_second…
15 0 Open
Dictionaries & sets easy

How to Build a Gradebook with Python Dictionaries and Sets

Create a gradebook dictionary from student names and grades, find top students with a set comprehension, and add extra credit with a dict comprehension.

dictionaries sets comprehensions
Python
def build_gradebook(students, grades):
    """Create a dictionary mapping student names to their grades."""
    return dict(zip(students, grades))


def find_top_students(gradebook, passing_grade=60):
    """Return a set of students with grades at or above the passing grade."""
    return {name for name, grade in grad…
12 0 Open
OOP & classes easy

Design a Data Helper Class in Python

Create a simple Object-Oriented data helper with DataPoint and Dataset classes that store, describe, and summarize coordinate points.

oop classes data-helper
Python
class DataPoint:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.label = None

    def describe(self):
        """Return a human-readable description of the data point."""
        base = f"DataPoint(x={self.x}, y={self.y})"
        return f"{base}, label='{self.label}'" if self.label e…
15 0 Open
Comprehensions & generators easy

Write Data Helpers with Comprehensions and Generators in Python

Demonstrates list, dict, and set comprehensions plus generator expressions and generator functions for building concise data helpers.

comprehensions generators data-helpers
Python
# Basic comprehensions and generators demo

# List comprehension: squares of evens
squares = [x * x for x in range(10) if x % 2 == 0]
print("List comp:", squares)

# Dictionary comprehension: char -> count
text = "hello"
char_counts = {c: text.count(c) for c in set(text)}
print("Dict comp:", char_counts)

# Set compre…
10 0 Open
AI & LLM integration patterns easy

How to Create a Simple Data Helper in Python for LLM Projects

Create a beginner-friendly Python class that stores, filters, and serializes data records for AI/LLM workflows.

data-helper json llm
Python
import json
from typing import Any, Dict, List, Optional


class DataHelper:
    """Simple helper for beginners to manage data in AI/LLM projects."""

    def __init__(self, data: Optional[List[Dict[str, Any]]] = None) -> None:
        self.data: List[Dict[str, Any]] = data or []

    def add_item(self, item: Dict[str…
14 0 Open
Cloud + Python easy

How to Create a JSON Data Helper in Python

A beginner-friendly DataHelper class that safely reads and writes JSON files with timestamps to a local data directory.

json files data-helper
Python
from datetime import datetime
from pathlib import Path
import json


class DataHelper:
    """Simple helper for reading/writing JSON files safely."""

    def __init__(self, base_dir="data"):
        self.base_dir = Path(base_dir)
        self.base_dir.mkdir(exist_ok=True)

    def save(self, filename, data):
        …
12 0 Open
Modern tooling easy

How to Load and Inspect CSV Data with a Dataclass Helper in Python

This code defines a DataHelper dataclass that reads a CSV file into a list of dictionaries and prints basic dataset information.

csv dataclass pathlib
Python
from pathlib import Path
from dataclasses import dataclass
from typing import Any


@dataclass
class DataHelper:
    """Simple helper for loading and inspecting CSV data."""
    filepath: Path

    def load_csv(self, *, delimiter: str = ",") -> list[dict[str, Any]]:
        """Read CSV into a list of dictionaries."""
…
16 0 Open
Modern tooling easy

How to Load and Save CSV and JSON Files in Python

A beginner-friendly data helper that loads or saves CSV and JSON files using only the Python standard library, with automatic format detection from the file extension.

csv json file-io
Python
from pathlib import Path
import json
import csv


def load_data(file_path):
    """Load CSV or JSON data from disk based on file extension."""
    path = Path(file_path)
    if path.suffix == ".json":
        with path.open() as f:
            return json.load(f)
    elif path.suffix == ".csv":
        with path.open(…
13 0 Open
Modern tooling easy

How to Save and Load JSON Files in Python

Create a simple data helper to save Python dictionaries as pretty-printed JSON files and load them back reliably using pathlib and the stdlib json module.

json pathlib file-io
Python
import json
from pathlib import Path
from typing import Any


def save_json(data: Any, filename: str) -> None:
    """Save data as pretty-printed JSON to the current directory."""
    path = Path(filename)
    with path.open("w", encoding="utf-8") as f:
        json.dump(data, f, indent=2, ensure_ascii=False)


def lo…
11 0 Open
System design patterns easy

Create a Data Helper Class in Python

A reusable DataHelper class that saves and loads JSON and CSV files from a configurable base directory, with automatic header detection for CSV.

data-helper json csv
Python
import json
import csv
from pathlib import Path

class DataHelper:
    def __init__(self, base_path="."):
        self.base_path = Path(base_path)
        self.base_path.mkdir(exist_ok=True)

    def save_json(self, data, filename):
        path = self.base_path / filename
        with open(path, "w") as f:
          …
15 0 Open
System design patterns easy

How to Implement a Data Helper Class in Python

Build a beginner-friendly DataHelper class using dataclasses and key system design patterns like Command, Strategy, and Map.

dataclass data-helper design-patterns
Python
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional


@dataclass
class DataHelper:
    """A beginner-friendly data utility with common system design patterns."""
    data: List[Dict[str, Any]] = field(default_factory=list)

    def add_record(self, r…
13 0 Open
Microservices patterns easy

How to Implement a Data Helper for Microservices in Python

Create a reusable helper class to serialize, deserialize, and wrap data for microservice communication using dataclasses and JSON.

microservices json dataclass
Python
import json
from dataclasses import dataclass, asdict
from typing import Any, Dict, List


@dataclass
class ServiceResponse:
    status: str
    data: Any
    message: str = ""


class DataHelper:
    """Simple helper for microservice data handling."""

    @staticmethod
    def serialize(data: Dict[str, Any]) -> str:…
13 0 Open
ML engineering pipelines easy

Build a Data Helper Class in Python for ML Pipelines

A beginner-friendly Python class that summarizes, filters, and exports ML dataset rows as JSON.

data-helper ml-pipeline json
Python
from typing import List, Dict, Any
import json

class DataHelper:
    """Beginner-friendly helpers for ML data pipelines."""
    
    def __init__(self, data: List[Dict[str, Any]]):
        self.data = data
        self.keys = list(data[0].keys()) if data else []
    
    def summary(self) -> Dict[str, Any]:
        "…
16 0 Open
Database scaling & optimization easy

How to Create a Data Helper Class in Python for JSON Files

Build a beginner-friendly Python helper class to read, write, filter, and summarize JSON data files with clean, reusable methods.

json data-helper file-io
Python
import json
from pathlib import Path


class DataHelper:
    """Simple beginner-friendly helper for reading and writing JSON data files."""

    @staticmethod
    def read_json(filename):
        file_path = Path(filename)
        if file_path.exists():
            with file_path.open("r", encoding="utf-8") as f:
    …
13 0 Open
Production deployment patterns easy

How to Implement a Data Helper Class in Python for Production Deployments

Build an environment-aware data helper in Python that loads config, extracts, transforms, and reports on JSON data using small, testable functions.

data-helper production json
Python
"""Production-style data helper for beginners.

Demonstrates:
- environment-aware config
- central data extraction
- small, testable functions
"""

import os
import json
from pathlib import Path
from typing import List, Dict, Any


def load_config(env: str = os.getenv("APP_ENV", "development")) -> Dict[str, Any]:
    …
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.