Reference library

Python Code Samples

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

19 matches
Lists & loops easy

How to Normalize a List of Numbers in Python

This Python function normalizes a list of numeric values to the range [0, 1] using min-max scaling, returning a new list and leaving the original unchanged.

lists loops normalization
Python
def normalize(data):
    """
    Normalize a list of numeric values to the range [0, 1].
    Returns a new list, leaving the original unchanged.
    """
    if not data:
        return []
    
    min_val = min(data)
    max_val = max(data)
    
    # Handle the edge case where all values are identical
    if min_val …
17 0 Open
Files & data easy

How to Filter CSV Rows by Column Value in Python

Filter CSV rows based on a column value condition using the standard csv module and a lambda function.

csv filter file-io
Python
import csv

def filter_csv(input_file, output_file, column, condition):
    with open(input_file, newline='', encoding='utf-8') as infile, \
         open(output_file, 'w', newline='', encoding='utf-8') as outfile:
        reader = csv.DictReader(infile)
        fieldnames = reader.fieldnames
        writer = csv.Dict…
18 0 Open
Files & data easy

How to Parse NDJSON Lines into a List in Python

Reads a JSON-lines (NDJSON) file line by line and converts each non-empty line into a Python object, returning a list.

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


def parse_ndjson(file_path: str) -> list:
    data = []
    with Path(file_path).open("r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if line:
                data.append(json.loads(line))
    return data


if __name__ == "__main__"…
12 0 Open
Dictionaries & sets easy

How to Count Tags with Sets and Dictionaries in Python

Count tag frequencies and collect unique tags from a list of dictionaries using Counter and sets in Python.

collections counter sets
Python
from collections import Counter
import json


def count_tags(entries):
    """Count tag frequencies across a list of entry dicts, using sets/dicts."""
    tag_counter = Counter()
    all_tags = set()
    for entry in entries:
        tags = set(entry["tags"])
        all_tags.update(tags)
        tag_counter.update(ta…
11 0 Open
Dictionaries & sets easy

How to Filter a List of Dictionaries by Category in Python

Filter a list of dictionaries to include only records whose category is in an allowed set.

dictionary set filter
Python
def filter_data(records, categories):
    """Return only records whose category is in the allowed set."""
    allowed = set(categories)
    filtered = []
    for record in records:
        if record["category"] in allowed:
            filtered.append(record)
    return filtered


if __name__ == "__main__":
    data = …
12 0 Open
Dictionaries & sets easy

How to Group Data by Category in Python with a Split Data Helper

This code groups a list of (category, item) pairs into a dictionary where each key is a category and each value is a list of items belonging to that category.

dictionary grouping iterable
Python
def split_data(categories):
    """
    Group data items into buckets based on a key function.
    Returns a dict where keys are bucket names and values are lists of items.
    """
    buckets = {}
    for category, item in categories:
        if category not in buckets:
            buckets[category] = []
        buck…
14 0 Open
OOP & classes easy

How to merge dictionaries by a key in Python with a class

This code defines a DataMerger class that collects dictionary records and merges them by a specified key, combining fields from multiple records with the same key.

classes dictionaries merging
Python
class DataMerger:
    def __init__(self):
        self.records = []

    def add_record(self, record):
        if isinstance(record, dict):
            self.records.append(record)
        else:
            raise TypeError("Record must be a dictionary")

    def merge_by_key(self, key):
        merged = {}
        for …
13 0 Open
Algorithms & data structures easy

How to Combine filter and map with a List Comprehension in Python

This Python code demonstrates how to combine filtering and mapping in a single list comprehension and shows the equivalent filter() and map() approach.

list-comprehension filter map
Python
def square(x):
    return x * x

def is_even(x):
    return x % 2 == 0

numbers = [1, 2, 3, 4, 5, 6, 7, 8]

result = [square(x) for x in numbers if is_even(x)]

print(f"Original numbers: {numbers}")
print(f"Squares of even numbers: {result}")

# Combined filter + map equivalent
filtered = filter(is_even, numbers)
mapp…
13 0 Open
Data pipelines & processing easy

Add a UUID Surrogate Key to Each Row in a CSV with Python

Generate a unique UUID string for every row in a CSV file using the standard-library uuid and csv modules.

csv uuid surrogate-key
Python
import uuid
import csv

def add_surrogate_key(filename):
    with open(filename, newline='') as f_in:
        reader = csv.DictReader(f_in)
        rows = list(reader)

    for row in rows:
        row['surrogate_key'] = str(uuid.uuid4())

    with open(filename, 'w', newline='') as f_out:
        writer = csv.DictWri…
14 0 Open
Data pipelines & processing easy

Create Data Helper Functions in Python for Beginners

Build reusable Python helper functions to load, filter, sort, summarize, and save JSON data — a beginner-friendly starting point for small data pipelines.

json pipeline helpers
Python
import json
from pathlib import Path
from typing import Any, Dict, List


def load_json_file(filepath: str) -> Dict[str, Any]:
    """Load JSON data from a file."""
    with Path(filepath).open("r", encoding="utf-8") as file:
        return json.load(file)


def filter_by_key(
    data: List[Dict[str, Any]], key: str,…
14 0 Open
Data pipelines & processing easy

Group Python Events into Sessions with a Gap Timeout

Groups timestamped events into sessions, starting a new session when the time gap exceeds a specified timeout.

sessions grouping datetime
Python
from itertools import groupby
from datetime import datetime, timedelta

def session_window_group(events, gap_seconds=300):
    """Group events into sessions where gap > gap_seconds starts a new session."""
    if not events:
        return []
    
    events = sorted(events, key=lambda x: x[0])
    sessions = []
    c…
13 0 Open
Data pipelines & processing easy

How to Build a Simple Data Pipeline in Python

A beginner-friendly data pipeline that loads JSON, filters records by a field value, and aggregates counts per category.

pipeline json aggregation
Python
import json
from pathlib import Path


def load_json(filepath: str | Path) -> list[dict]:
    """Load a JSON file containing a list of records."""
    with Path(filepath).open("r", encoding="utf-8") as f:
        return json.load(f)


def filter_records(records: list[dict], field: str, value) -> list[dict]:
    """Kee…
10 0 Open
Data pipelines & processing easy

How to Filter Data in Python

Filter a list of dictionaries by exact key-value matches or numerical ranges using concise list comprehensions.

filtering list-comprehension dictionaries
Python
from typing import List, Dict, Any


def filter_data(
    data: List[Dict[str, Any]], key: str, value: Any
) -> List[Dict[str, Any]]:
    """Return records where data[key] equals value."""
    return [record for record in data if record.get(key) == value]


def filter_by_range(
    data: List[Dict[str, Any]], key: str…
12 0 Open
Data pipelines & processing easy

How to Parse Data in Python: A Beginner's Helper

This helper parses a JSON payload, extracts user names, emails, and signup dates, then summarizes the results.

json parsing data-processing
Python
import json
from datetime import datetime
from typing import Dict, List


def parse_data(payload: str) -> Dict[str, List]:
    """Parse a JSON payload and extract useful fields."""
    raw = json.loads(payload)
    users = raw.get("users", [])

    parsed = {
        "names": [],
        "emails": [],
        "signup_…
15 0 Open
Data pipelines & processing easy

How to Process CSV Data in Python with a Data Helper

Build a beginner-friendly data helper in Python that loads a CSV file, filters rows by a condition, and summarizes numeric fields.

csv data-processing pathlib
Python
import csv
from pathlib import Path

DATA = [
    {"name": "Alice", "score": 88, "passed": True},
    {"name": "Bob", "score": 42, "passed": False},
    {"name": "Carol", "score": 95, "passed": True},
]


def load_csv(file_path: Path) -> list[dict]:
    with file_path.open(newline="", encoding="utf-8") as f:
        r…
13 0 Open
Data pipelines & processing easy

How to detect anomalies in a column using z-score in Python

Detect outliers in a list of numbers using z-score statistics, flagging values that deviate significantly from the mean.

anomaly-detection z-score statistics
Python
import random

def z_score_anomaly_detection(data, threshold=2.0):
    """
    Detect anomalies in a list of numbers using z-score.
    """
    mean = sum(data) / len(data)
    variance = sum((x - mean) ** 2 for x in data) / len(data)
    std_dev = variance ** 0.5
    
    if std_dev == 0:
        return []
    
    a…
14 0 Open
Data pipelines & processing easy

Idempotent Pipeline Dedupe by Record ID Set in Python

Filters records against a persistent set of seen IDs, returning only new ones and the updated set for idempotent pipeline processing.

deduplication idempotency pipelines
Python
def dedupe_records(records, seen_ids=None):
    """Return records whose id has not been seen before."""
    if seen_ids is None:
        seen_ids = set()
    unique = []
    for record in records:
        record_id = record.get("id")
        if record_id not in seen_ids:
            seen_ids.add(record_id)
           …
12 0 Open
Database scaling & optimization easy

How to Limit a Result Set to Top N Rows in Python

Sort a list of dictionaries by a numeric key and return only the top N results, formatted as a readable ranked list.

sorting slicing top-n
Python
import random

def top_n_mock(limit: int = 5):
    """Return a formatted top-N result set as a mock example."""
    # Simulated data source
    scores = [
        {"name": "Alice", "score": 87},
        {"name": "Bob", "score": 92},
        {"name": "Charlie", "score": 78},
        {"name": "Diana", "score": 95},
    …
16 0 Open
Production deployment patterns easy

How to Build a Data Helper for Production Deployment in Python

Build a reusable DataHelper class that loads configs, validates required keys, normalizes string values, and logs schema details — a production-ready data processing pattern.

json pathlib data-processing
Python
import json
from pathlib import Path
from typing import Any, Dict

class DataHelper:
    """Common data processing patterns for production deployment."""
    
    def __init__(self, config_path: str | Path):
        self.config_path = Path(config_path)
        self.config = self._load_config()
    
    def _load_confi…
14 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.