Reference library

Python Code Samples

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

10 matches
Lists & loops easy

How to Flatten One Level of a Nested List in Python

Flattens exactly one level of a nested list by extending the output with each inner list and appending non-list items.

flatten nested list list comprehension
Python
def flatten_one_level(nested_list):
    """Flatten one level of a nested list."""
    flattened = []
    for item in nested_list:
        if isinstance(item, list):
            flattened.extend(item)
        else:
            flattened.append(item)
    return flattened

if __name__ == "__main__":
    # Example with mi…
15 0 Open
Lists & loops easy

How to Flatten a Deeply Nested List in Python Recursively

A recursive function that flattens arbitrarily deep nested lists into a single flat list using isinstance checks.

recursion flatten lists
Python
def flatten(nested_list):
    if not nested_list:
        return []
    if isinstance(nested_list[0], list):
        return flatten(nested_list[0]) + flatten(nested_list[1:])
    return [nested_list[0]] + flatten(nested_list[1:])


if __name__ == "__main__":
    data = [1, [2, [3, [4, [5]]]], [6, [7, [8, [9]]]], 10]
 …
13 0 Open
Dictionaries & sets easy

Flatten a Nested Dict to Dot Notation Keys in Python

Recursively flatten a nested dictionary into a flat dictionary with dot-separated keys using a small recursive function.

dict flatten recursion
Python
def flatten_dict(nested, parent_key='', sep='.'):
    items = {}
    for key, value in nested.items():
        new_key = f"{parent_key}{sep}{key}" if parent_key else key
        if isinstance(value, dict):
            items.update(flatten_dict(value, new_key, sep))
        else:
            items[new_key] = value
    …
11 0 Open
Dictionaries & sets medium

Unflatten Dot Keys to Nested Dict in Python

Convert a flat dictionary with dot-separated keys into a nested dictionary structure using recursive setdefault loops.

dictionaries nested flatten
Python
def unflatten_dot_keys(flat_dict):
    result = {}
    for flat_key, value in flat_dict.items():
        parts = flat_key.split(".")
        current = result
        for part in parts[:-1]:
            current = current.setdefault(part, {})
        current[parts[-1]] = value
    return result


if __name__ == "__main_…
14 0 Open
Algorithms & data structures easy

How to Flatten List of Dict Values in Python

This code flattens the values of a list of dictionaries into a single list, handling both list values and scalar values.

flatten dictionaries lists
Python
def flatten_dict_values(dicts):
    flattened = []
    for d in dicts:
        for value in d.values():
            if isinstance(value, list):
                flattened.extend(value)
            else:
                flattened.append(value)
    return flattened


if __name__ == "__main__":
    data = [
        {"a": …
12 0 Open
Comprehensions & generators easy

Flatten a Nested List in Python (Recursive Generator)

Recursively flatten arbitrarily nested lists into a single-level list using both a function and a generator with `yield from`.

recursion generators flatten
Python
def flatten(nested_list):
    """Recursively flatten a nested list into a single-level list."""
    result = []
    for item in nested_list:
        if isinstance(item, list):
            result.extend(flatten(item))
        else:
            result.append(item)
    return result


def flatten_generator(nested_list):
…
14 0 Open
Comprehensions & generators easy

How to Delegate Iteration to a Subgenerator with yield from in Python

Use yield from to delegate iteration from one generator to a subgenerator, flattening nested generator output into a single sequence.

generators yield-from delegation
Python
def subgenerator():
    yield "first"
    yield "second"
    yield "third"


def delegate():
    yield "before delegation"
    yield from subgenerator()
    yield "after delegation"


if __name__ == "__main__":
    for item in delegate():
        print(item)
13 0 Open
AI & LLM integration patterns medium

How to Build a Data Helper for LLM Prompts in Python

A beginner-friendly helper class that flattens nested dictionaries, formats prompt templates, and safely parses JSON for AI/LLM pipelines.

llm prompt-engineering data-prep
Python
import json
from typing import Any, Dict, List, Optional


class DataHelper:
    """Simple helper class for working with data in AI/LLM pipelines."""
    
    def __init__(self, data: Optional[Dict[str, Any]] = None) -> None:
        self.data = data or {}
    
    def flatten(self, prefix: str = "") -> Dict[str, Any]…
17 0 Open
Data pipelines & processing easy

How to Explode an Array Field into Multiple Rows in Python

This code flattens a list of dictionaries by exploding each array field value into its own row, duplicating the other fields as needed.

data transformation arrays flattening
Python
from collections import defaultdict

data = [
    {"id": 1, "name": "Alice", "tags": ["python", "data", "ai"]},
    {"id": 2, "name": "Bob", "tags": ["web", "devops"]},
    {"id": 3, "name": "Carol", "tags": []},
]

def explode_array_field(records, array_field):
    result = []
    for record in records:
        for v…
11 0 Open
Database scaling & optimization medium

Simulate a GIN Index for JSONB in Python

Build a mock Generalized Inverted Index (GIN) that flattens JSON documents into key-value tokens for fast lookup queries, mimicking PostgreSQL JSONB indexing.

jsonb gin-index inverted-index
Python
import json
import random
from collections import defaultdict

# Mock GIN (Generalized Inverted Index) for JSONB key-value pairs
class GINIndex:
    def __init__(self):
        self.posting_lists = defaultdict(list)  # token -> list of doc_ids
    
    def index(self, doc_id, json_obj):
        """Index a JSON documen…
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.