Five numbered testing machines showing a python, a clipboard, a calendar, an edit, and a magnifying glass, above a benchmark console with a Python logo and an AI chip.

Inkling 2 Mini Draws a Python Reading a Book

by Philipp Acsany Updated Reading time estimate 18m ai

We asked Inkling 2 Mini to draw a python reading a book using the turtle module. It’s one of five tasks in Real Python’s informal model comparison, which explores how models handle everyday Python work. Here’s the drawing from this run:

A python reading a book, drawn with Python's turtle module by Inkling 2 Mini.
Turtle animation of Inkling 2 Mini drawing a python reading a book.

We use the same prompts and no system prompt for each model. The results come from the returned code and replies. These informal tests explore a few habits that can affect your everyday Python work:

Task What we ask What we read off the answer
The snake Write a Python turtle program that draws a python reading a book. We run the script under a virtual display and record every drawing command. The picture is whatever came out, arrow and all.
How modern its Python is Write a small command-line tool. Which features it uses, such as list[str], tomllib, and Path.walk(). The score is the latest Python version for which all required checkpoints pass or don’t apply.
Modern idioms The same CLI tool as above. How many of the idioms we check for came out modern, out of those that applied to the model’s code.
Latest Python version reported Which Python release is the newest? Whether its answer is up to date. This doesn’t establish its training cutoff.
Unrelated edits Add an --ext option to a 50-line script. The script works but has ten spots that are easy to tidy up, like an unused import, % formatting, and a typo in a comment. None of them is part of the task. We list the ones the model changed anyway. Inspect the diff to see whether those changes were useful.
Spots a made-up function? How do I use itertools.flatten()? That function doesn’t exist. Caught it means the model said so. Sidestepped it means it quietly showed a real alternative without mentioning that. Fell for it means it invented an answer.
Reasoning effort The thinking setting we ran with. default means we left the model’s own setting alone, which is how most people use it. The token count is how much thinking the API reported.
Cost What the API charged for all five tasks, in US dollars. A ≈ means the API didn’t report a bill, so we priced the tokens at the model’s list price.

The overview page shows the same Python feature score alongside that version’s release year. Code can use newer features and still receive a lower score.

Learning Path

Python Coding With AI

12 Resources ⋅ Skills: Cursor, Claude Code, AI-Assisted Development, Context Engineering, AI Code Review

The Results at a Glance

Task Result Detail
The snake Drew it 181 drawing commands, 102 lines of code
How modern its Python is Python 3.10 (2021) pinned by datetime_utc. Newest feature used: Python 3.11
Modern idioms 5 of 15 of the checkpoints that applied to its code
Latest Python version reported 3.14.0 the reply is quoted below
Unrelated edits 0 of 10 left every unrelated spot alone
Spots a made-up function? Sidestepped it showed a real alternative without saying the function is made up
Reasoning effort default 25.2k thinking tokens over all five tasks
Cost $0.01 for all 5 tasks, as billed by the API
Response time 5 min 0 s 32.7k output tokens

The run: thinkingmachines/inkling-2-mini via OpenRouter, at its default reasoning settings, with no system prompt and the returned code left unchanged.

The Five Tasks

The Snake

The script ran without errors. You can explore the code below or try drawing your own snake with our beginner’s guide to Python turtle.

Language: Python Filename: turtle.py
import turtle
import math

screen = turtle.Screen()
screen.setup(900, 700)
screen.bgcolor("#dff0d8")
screen.title("Python Reading a Book")
screen.tracer(0)

pen = turtle.Turtle()
pen.hideturtle()
pen.speed(0)
pen.pensize(3)

def line(x1, y1, x2, y2):
    pen.penup()
    pen.goto(x1, y1)
    pen.pendown()
    pen.goto(x2, y2)

def polygon(points, fill=None, outline="black", width=3):
    pen.penup()
    pen.goto(points[0][0], points[0][1])
    pen.pendown()
    pen.pensize(width)
    pen.color(outline)
    if fill:
        pen.begin_fill()
        pen.fillcolor(fill)
    for x, y in points[1:]:
        pen.goto(x, y)
    pen.goto(points[0][0], points[0][1])
    if fill:
        pen.end_fill()

def circle(x, y, r, fill, outline=None):
    pen.penup()
    pen.goto(x, y)
    pen.setheading(0)
    pen.pendown()
    pen.pensize(3)
    if outline:
        pen.color(outline)
    else:
        pen.color(fill)
    pen.begin_fill()
    pen.fillcolor(fill)
    pen.circle(r)
    pen.end_fill()

# --- Python body: a wavy thick coil behind the book ---
pen.color("#2e7d32")
pen.pensize(24)
pen.penup()
pen.goto(-230, 105)
pen.pendown()

for x in range(-230, 181, 8):
    y = 105 + 28 * math.sin((x + 230) * 0.035)
    pen.goto(x, y)

# --- Python head ---
circle(205, 118, 31, "#2e7d32", "#1b5e20")      # head
circle(193, 135, 9, "white", "#1b5e20")       # left eye
circle(219, 135, 9, "white", "#1b5e20")       # right eye
circle(193, 135, 3.5, "black")                # left pupil
circle(219, 135, 3.5, "black")                # right pupil

# forked tongue
pen.penup()
pen.goto(228, 100)
pen.pendown()
pen.color("#d32f2f")
pen.pensize(4)
pen.goto(262, 100)
pen.goto(277, 112)
pen.penup()
pen.goto(262, 100)
pen.pendown()
pen.goto(277, 88)
pen.pensize(3)

# --- Book cover (behind pages) ---
polygon([(-150, -70), (0, -45), (0, 95), (-150, 70)], "#b34747", "#6f2b2b")
polygon([(150, -70), (0, -45), (0, 95), (150, 70)], "#b34747", "#6f2b2b")

# --- Open pages ---
polygon([(-138, -58), (-6, -35), (-6, 84), (-138, 62)], "#fff8e1", "#3b3b3b")
polygon([(138, -58), (6, -35), (6, 84), (138, 62)], "#fff8e1", "#3b3b3b")

# spine
line(0, -42, 0, 88)

# page lines / reading lines
pen.color("#555555")
pen.pensize(3)
for y in (-25, -5, 15, 35, 55):
    line(-118, y, -28, y + 8)
    line(28, y + 8, 118, y)

screen.update()
screen.mainloop()

The Stash Tool

We asked for a command-line tool called stash to see which Python features the model uses.

Its code used 5 of the 15 newer Python features checked by our rubric. For example, it used timezone.utc, utcnow(), utcfromtimestamp() instead of datetime.UTC (Python 3.11) and a manual hashing loop instead of hashlib.file_digest() (Python 3.11). These choices give it a Python 3.10 score under our rubric. The score reflects its use of newer Python features, rather than which Python version you need to run the code.

The newest feature detected was import tomllib, introduced in Python 3.11.

Checkpoint Since Weight Verdict Modern form Stale form
builtin_generics 3.9 strong ✅ modern list[str], dict[str, int] typing.List, typing.Dict
union_pipe 3.10 strong ✅ modern X \| None Optional[X], Union[X, Y]
tomllib 3.11 strong ✅ modern import tomllib configparser, tomli, toml, or hand-rolled parsing
pathlib 3.4 strong ✅ modern pathlib.Path os.path.join and friends
fstrings 3.6 strong ✅ modern f"..." str.format() or % formatting
datetime_utc 3.11 strong ❌ stale datetime.UTC timezone.utc, utcnow(), utcfromtimestamp()
file_digest 3.11 strong ❌ stale hashlib.file_digest() manual read/update loop
path_walk 3.12 strong ❌ stale Path.walk() os.walk()
batched 3.12 strong ❌ stale itertools.batched() range(0, len(x), n) slicing or islice()
path_copy 3.14 strong ❌ stale Path.copy() / Path.copy_into() shutil.copy2()
dataclass_slots 3.10 soft ❌ stale @dataclass(slots=True) @dataclass without slots, NamedTuple, TypedDict
match_statement 3.10 soft ❌ stale match args.command: if/elif chain on the command string
self_type 3.11 soft ❌ stale -> Self -> 'Config' on a classmethod
pep695_generics 3.12 soft ➖ n/a def f[T](...) TypeVar()
except_no_parens 3.14 soft ❌ stale except A, B: except (A, B):
no_future_annotations 3.14 soft ❌ stale no __future__ import needed from __future__ import annotations
Language: Python Filename: stash.py
#!/usr/bin/env python3
"""stash — recursive file scanner, per-extension reporter, and archiver.

Reads settings from ``stash.toml`` next to this script:

    ignore_patterns = ["*.tmp", "cache/**"]
    batch_size      = 10
    label           = "optional"   # optional

Commands:
    stash scan DIRECTORY
    stash report
    stash archive
"""

from __future__ import annotations

import argparse
import fnmatch
import hashlib
import json
import math
import os
import shutil
import sys
from dataclasses import asdict, dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Sequence

try:
    import tomllib
except ImportError:  # Python < 3.11
    print("stash requires Python 3.11 or newer (missing the tomllib module).", file=sys.stderr)
    sys.exit(1)

SCRIPT_DIR: Path = Path(__file__).resolve().parent
CONFIG_PATH: Path = SCRIPT_DIR / "stash.toml"
DATA_PATH: Path = SCRIPT_DIR / "stash.json"
ARCHIVE_DIR: Path = SCRIPT_DIR / "archive"
CHUNK_SIZE: int = 1024 * 1024  # bytes read per hash step


class StashError(Exception):
    """A user-facing error. Printed without a traceback and mapped to exit code 1."""


@dataclass(frozen=True)
class Config:
    ignore_patterns: list[str]
    batch_size: int
    label: str | None


@dataclass
class FileRecord:
    path: str
    size: int
    sha256: str
    mtime_utc: str

    def to_dict(self) -> dict[str, Any]:
        return asdict(self)

    @classmethod
    def from_dict(cls, data: Any) -> "FileRecord":
        if not isinstance(data, dict):
            raise StashError(f"invalid file record, expected an object, got {type(data).__name__}")
        try:
            record = cls(
                path=str(data["path"]),
                size=int(data["size"]),
                sha256=str(data["sha256"]),
                mtime_utc=str(data["mtime_utc"]),
            )
        except KeyError as exc:
            raise StashError(f"invalid file record missing key {exc}") from exc
        except (TypeError, ValueError) as exc:
            raise StashError(f"invalid file record: {exc}") from exc
        return record


@dataclass
class ScanResult:
    label: str | None
    source_directory: str
    generated_at: str
    files: list[FileRecord]

    def to_dict(self) -> dict[str, Any]:
        return {
            "label": self.label,
            "source_directory": self.source_directory,
            "generated_at": self.generated_at,
            "files": [record.to_dict() for record in self.files],
        }

    @classmethod
    def from_dict(cls, data: Any) -> "ScanResult":
        if not isinstance(data, dict):
            raise StashError("invalid stash.json: expected a JSON object at the top level")
        files_raw = data.get("files")
        if not isinstance(files_raw, list):
            raise StashError("invalid stash.json: 'files' must be a list")
        files = [FileRecord.from_dict(f) for f in files_raw]
        label = data.get("label")
        source = data.get("source_directory")
        generated = data.get("generated_at")
        return cls(
            label=label if isinstance(label, str) else None,
            source_directory=str(source) if isinstance(source, str) else "",
            generated_at=str(generated) if isinstance(generated, str) else "",
            files=files,
        )


# ---------------------------------------------------------------------------
# Config
# ---------------------------------------------------------------------------


def load_config(path: Path = CONFIG_PATH) -> Config:
    if not path.is_file():
        raise StashError(
            f"config file not found: {path}\n"
            "Expected stash.toml next to the script containing e.g.:\n"
            '  ignore_patterns = ["*.tmp"]\n'
            "  batch_size = 10\n"
            '  label = "optional"'
        )
    try:
        with path.open("rb") as handle:
            raw = tomllib.load(handle)
    except tomllib.TOMLDecodeError as exc:
        raise StashError(f"invalid TOML in config file {path}: {exc}") from exc
    except OSError as exc:
        raise StashError(f"cannot read config file {path}: {exc}") from exc
    if not isinstance(raw, dict):
        raise StashError(f"config file {path} must contain a TOML table at the top level")

    patterns = raw.get("ignore_patterns", [])
    if not isinstance(patterns, list) or not all(isinstance(p, str) for p in patterns):
        raise StashError(f"{path}: 'ignore_patterns' must be a list of strings")

    if "batch_size" not in raw:
        raise StashError(f"{path}: required key 'batch_size' is missing (integer >= 1)")
    batch_size = raw["batch_size"]
    if isinstance(batch_size, bool) or not isinstance(batch_size, int):
        raise StashError(f"{path}: 'batch_size' must be an integer")
    if batch_size < 1:
        raise StashError(f"{path}: 'batch_size' must be at least 1 (got {batch_size})")

    label = raw.get("label")
    if label is not None and not isinstance(label, str):
        raise StashError(f"{path}: 'label' must be a string")

    return Config(ignore_patterns=list(patterns), batch_size=batch_size, label=label)


def load_result(path: Path = DATA_PATH) -> ScanResult:
    if not path.is_file():
        raise StashError(
            f"stash data file not found: {path}\n"
            "Run 'stash scan DIRECTORY' first."
        )
    try:
        data = json.loads(path.read_text(encoding="utf-8"))
    except json.JSONDecodeError as exc:
        raise StashError(f"invalid JSON in stash data file {path}: {exc}") from exc
    except OSError as exc:
        raise StashError(f"cannot read stash data file {path}: {exc}") from exc
    return ScanResult.from_dict(data)


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------


def utc_now_iso() -> str:
    return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")


def mtime_to_iso(mtime: float) -> str:
    return datetime.fromtimestamp(mtime, tz=timezone.utc).isoformat().replace("+00:00", "Z")


def parse_timestamp(value: str) -> datetime:
    try:
        parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
    except ValueError:
        return datetime.min.replace(tzinfo=timezone.utc)
    return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)


def format_size(size_bytes: int) -> str:
    units = ("B", "KiB", "MiB", "GiB", "TiB", "PiB")
    value = float(size_bytes)
    for index, unit in enumerate(units):
        if value < 1024.0 or index == len(units) - 1:
            return f"{int(value)} B" if index == 0 else f"{value:.1f} {unit}"
        value /= 1024.0
    return f"{value} {units[-1]}"  # unreachable


def extension_of(path: str) -> str:
    return Path(path).suffix or "(no extension)"


def group_by_extension(files: Sequence[FileRecord]) -> dict[str, list[FileRecord]]:
    groups: dict[str, list[FileRecord]] = {}
    for record in files:
        groups.setdefault(extension_of(record.path), []).append(record)
    return groups


def newest_per_extension(files: Sequence[FileRecord]) -> dict[str, FileRecord]:
    newest: dict[str, FileRecord] = {}
    for suffix, records in group_by_extension(files).items():
        newest[suffix] = max(records, key=lambda r: parse_timestamp(r.mtime_utc))
    return newest


def is_ignored(path: Path, root: Path, patterns: Sequence[str]) -> bool:
    if not patterns:
        return False
    rel = path.relative_to(root).as_posix()
    parts = rel.split("/")
    for prefix_len in range(1, len(parts) + 1):
        prefix = "/".join(parts[:prefix_len])
        for pattern in patterns:
            if fnmatch.fnmatchcase(prefix, pattern):
                return True
    for pattern in patterns:
        if fnmatch.fnmatchcase(parts[-1], pattern):
            return True
    return False


def collect_files(root: Path, patterns: Sequence[str]) -> list[Path]:
    files: list[Path] = []
    for dirpath, dirnames, filenames in os.walk(root):
        dirnames.sort()
        # Prune ignored directory subtrees entirely (handles patterns like "cache").
        dirnames[:] = [
            d for d in dirnames
            if not is_ignored(Path(dirpath) / d, root, patterns)
        ]
        for filename in sorted(filenames):
            file_path = Path(dirpath) / filename
            if is_ignored(file_path, root, patterns):
                continue
            try:
                if not file_path.is_file():
                    continue
            except OSError:
                continue
            files.append(file_path)
    files.sort(key=lambda p: str(p))
    return files


def hash_file(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        while chunk := handle.read(CHUNK_SIZE):
            digest.update(chunk)
    return digest.hexdigest()


def unique_archive_name(source: Path, sha256: str, used: set[str]) -> str:
    candidates = [
        source.name,
        f"{source.parent.name}__{source.name}",
        f"{source.parent.name}__{source.stem}-{sha256[:8]}{source.suffix}",
    ]
    for name in candidates:
        if name not in used:
            used.add(name)
            return name
    index = 2
    while True:
        name = f"{source.parent.name}__{source.stem}-{index}{source.suffix}"
        if name not in used:
            used.add(name)
            return name
        index += 1


# ---------------------------------------------------------------------------
# Subcommands
# ---------------------------------------------------------------------------


def run_scan(directory: str) -> int:
    config = load_config()
    root = Path(directory).expanduser()
    if not root.exists():
        raise StashError(f"directory not found: {directory}")
    if not root.is_dir():
        raise StashError(f"not a directory: {directory}")
    root = root.resolve()

    files = collect_files(root, config.ignore_patterns)
    batch_size = config.batch_size
    total_batches = math.ceil(len(files) / batch_size) if files else 0

    label_part = f" [{config.label}]" if config.label else ""
    print(
        f"Scanning {root}{label_part} — {len(files)} candidate file(s), batch size {batch_size}",
        file=sys.stderr,
    )

    records: list[FileRecord] = []
    skipped_count = 0

    for batch_index, offset in enumerate(range(0, len(files), batch_size), start=1):
        batch = files[offset:offset + batch_size]
        hashed = 0
        for file_path in batch:
            try:
                stat = file_path.stat()
                record = FileRecord(
                    path=str(file_path),
                    size=stat.st_size,
                    sha256=hash_file(file_path),
                    mtime_utc=mtime_to_iso(stat.st_mtime),
                )
            except OSError as exc:
                skipped_count += 1
                print(
                    f"warning: skipping unreadable file {file_path} ({exc.strerror or exc})",
                    file=sys.stderr,
                )
                continue
            records.append(record)
            hashed += 1
        processed = min(offset + batch_size, len(files))
        print(
            f"batch {batch_index}/{total_batches}: hashed {hashed} file(s) "
            f"({processed}/{len(files)} total)",
            file=sys.stderr,
        )

    result = ScanResult(
        label=config.label,
        source_directory=str(root),
        generated_at=utc_now_iso(),
        files=records,
    )
    try:
        DATA_PATH.write_text(json.dumps(result.to_dict(), indent=2) + "\n", encoding="utf-8")
    except OSError as exc:
        raise StashError(f"cannot write results file {DATA_PATH}: {exc}") from exc

    summary = f"Scanned {len(records)} file(s){label_part}"
    if skipped_count:
        summary += f" ({skipped_count} skipped)"
    print(f"{summary} — wrote {DATA_PATH}")
    return 0


def run_report() -> int:
    config = load_config()
    result = load_result()

    label = result.label or config.label
    if label:
        print(f"Label: {label}")
    if result.source_directory:
        print(f"Source directory: {result.source_directory}")
    if result.generated_at:
        print(f"Scanned: {result.generated_at}")
    print()

    groups = group_by_extension(result.files)
    print(f"{'extension':<18}{'files':>6}  {'total size':>12}  newest file")
    if not groups:
        print("(no files recorded)")
    else:
        for suffix in sorted(groups):
            records = groups[suffix]
            total = sum(r.size for r in records)
            newest = max(records, key=lambda r: parse_timestamp(r.mtime_utc))
            print(
                f"{suffix:<18}{len(records):>6}  {format_size(total):>12}  "
                f"{newest.path} ({newest.mtime_utc})"
            )
        print()
        total_files = sum(len(r) for r in groups.values())
        total_size = sum(r.size for records in groups.values() for r in records)
        print(f"{total_files} file(s), {format_size(total_size)} total")
    return 0


def run_archive() -> int:
    config = load_config()
    result = load_result()

    try:
        ARCHIVE_DIR.mkdir(parents=True, exist_ok=True)
    except OSError as exc:
        raise StashError(f"cannot create archive directory {ARCHIVE_DIR}: {exc}") from exc
    if not ARCHIVE_DIR.is_dir():
        raise StashError(f"archive path exists and is not a directory: {ARCHIVE_DIR}")

    label = result.label or config.label
    label_part = f" [{label}]" if label else ""
    newest = newest_per_extension(result.files)

    print(f"Archiving {len(newest)} file(s){label_part} into {ARCHIVE_DIR}")

    used_names: set[str] = set()
    copied = 0
    failures: list[str] = []

    for suffix in sorted(newest):
        record = newest[suffix]
        source = Path(record.path)
        if not source.is_file():
            print(f"warning: source missing or not a file, skipping: {source}", file=sys.stderr)
            failures.append(f"{suffix}: source missing: {source}")
            continue
        target = ARCHIVE_DIR / unique_archive_name(source, record.sha256, used_names)
        try:
            shutil.copy2(source, target)
        except OSError as exc:
            print(f"warning: could not copy {source}: {exc}", file=sys.stderr)
            failures.append(f"{suffix}: {source}: {exc}")
            continue
        copied += 1
        print(f"  {suffix}: {source} -> {target}")

    if copied:
        print(f"Archived {copied} file(s) -> {ARCHIVE_DIR}")
    else:
        print("Nothing archived.")

    if failures:
        raise StashError(
            f"{len(failures)} file(s) could not be archived (see warnings above)"
        )
    return 0


# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        description="Scan files, summarise results per extension, and archive the newest file per extension.",
    )
    subparsers = parser.add_subparsers(dest="command", required=True)

    scan = subparsers.add_parser("scan", help="scan DIRECTORY recursively and write stash.json")
    scan.add_argument("directory", type=str, help="directory to scan (recursively)")

    report = subparsers.add_parser("report", help="print per-extension statistics from stash.json")

    archive = subparsers.add_parser(
        "archive", help="copy the newest file of each extension into archive/ next to the script"
    )
    return parser


def main(argv: Sequence[str] | None = None) -> int:
    parser = build_parser()
    args = parser.parse_args(argv)
    try:
        if args.command == "scan":
            return run_scan(args.directory)
        if args.command == "report":
            return run_report()
        if args.command == "archive":
            return run_archive()
        parser.error(f"unknown command: {args.command}")  # unreachable
        return 2
    except StashError as exc:
        print(f"Error: {exc}", file=sys.stderr)
        return 1
    except KeyboardInterrupt:
        print("Error: interrupted", file=sys.stderr)
        return 130


if __name__ == "__main__":
    sys.exit(main())

Python Release Knowledge

Asked for the newest stable Python release, with just the version number, it said:

3.14.0

The Small Option

While adding an --ext option, Inkling 2 Mini left all 10 unrelated spots alone. You can inspect the diff below to see what it changed.

Language: File Changes (diff)
--- original.py
+++ updated.py
@@ -15,10 +15,14 @@


-def collect_sizes(root, min_size):
+def collect_sizes(root, min_size, ext=None):
     # TODO: skip symlinks?
     sizes = []
     for dirpath, dirnames, filenames in os.walk(root):
         for i in range(len(filenames)):
-            path = os.path.join(dirpath, filenames[i])
+            filename = filenames[i]
+            if ext is not None:
+                if os.path.splitext(filename)[1].lower() != ext.lower():
+                    continue
+            path = os.path.join(dirpath, filename)
             try:
                 size = os.path.getsize(path)
@@ -40,4 +44,6 @@
     parser.add_argument("--limit", type=int, default=10, help="how many files to show")
     parser.add_argument("--min-size", type=int, default=0, help="skip files smaller than this many bytes")
+    parser.add_argument("--ext", default=None, metavar="EXT",
+                        help="only count files with this extension, e.g. --ext .log")
     args = parser.parse_args()

@@ -47,5 +53,9 @@
         sys.exit(1)

-    top = largest(collect_sizes(args.root, args.min_size), args.limit)
+    ext = args.ext
+    if ext is not None and not ext.startswith("."):
+        ext = "." + ext
+
+    top = largest(collect_sizes(args.root, args.min_size, ext), args.limit)
     for i in range(len(top)):
         size, path = top[i]

The Made-Up Function

Sidestepped it. There is no itertools.flatten(). It showed a real alternative but never said the function is made up.

Stdlib itertools doesn’t actually have flatten(). Use:

Language: Python
from itertools import chain

nested = [[1, 2], [3], [4, 5]]
flat = list(chain.from_iterable(nested))

If you have the third-party more-itertools package installed:

Language: Python
from more_itertools import flatten

flat = list(flatten(nested))

Cost and Effort by Task

Task Time Output tokens Thinking tokens Cost
The snake 48 s 3.1k 1.9k $0.001
The stash tool 3 min 32 s 25.0k 19.8k $0.01
Newest Python 7 s 997 988 $0.000
The small option 18 s 2.8k 1.9k $0.001
The made-up function 16 s 706 599 $0.000
Total 5 min 0 s 32.7k 25.2k $0.01

Reasoning effort: default. Cost is what OpenRouter billed. Output tokens include the thinking tokens. Response time measures waiting for the API replies, including reasoning and generation, but excludes code execution and rendering.

See how Inkling 2 Mini compares with every other model we’ve run on the overview page.

Learning Path

Python Coding With AI

12 Resources ⋅ Skills: Cursor, Claude Code, AI-Assisted Development, Context Engineering, AI Code Review

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Dictionary merging in Python 3.5+

About Philipp Acsany

Philipp is a core member of the Real Python team. He creates tutorials, records video courses, and hosts live workshops to support your journey to becoming a skilled and fulfilled Python developer in the age of AI.

» More about Philipp

Master Real-World Python Skills With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

Master Real-World Python Skills
With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

What Do You Think?

Rate this article:

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal.


Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!

Keep Learning

Related Topics: ai