Reference library

Python Code Samples

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

5 matches
Algorithms & data structures medium

How to Find Minimum Swaps to Sort an Array in Python

Calculate the minimum number of adjacent-free swaps needed to sort a permutation array using cycle detection in Python.

sorting cycles greedy
Python
def min_swaps_to_sort(arr):
    n = len(arr)
    arr_pos = sorted((val, idx) for idx, val in enumerate(arr))
    visited = [False] * n
    swaps = 0

    for i in range(n):
        if visited[i] or arr_pos[i][1] == i:
            continue

        cycle_size = 0
        j = i
        while not visited[j]:
            …
13 0 Open
Testing & modern typing medium

How to Use Mock Flip Mutation Testing in Python

Demonstrates how mutation testing tools flip Boolean literals (mock flip) in Python source to verify test suite effectiveness in catching logic changes.

mutation-testing testing bool
Python
import random

# In mutation testing, a "mock flip" intentionally changes a Boolean
# constant to False (or True) to see if the test suite catches it.
# This is a common "constant mutation" applied to a source file's literals.

def is_even(n: int) -> bool:
    """Return True if n is even. Contains a Boolean literal us…
13 0 Open
Microservices patterns medium

CQRS with Separate Read and Write Repositories in Python

Implement CQRS in Python with separate write and read repositories, using commands for mutations and frozen DTOs for queries.

cqrs repositories microservices
Python
from dataclasses import dataclass
from typing import Dict, List, Optional


# --- Write side: commands mutate state ---
@dataclass
class CreateUserCommand:
    id: int
    name: str


class UserWriteRepository:
    def __init__(self) -> None:
        self._store: Dict[int, Dict[str, object]] = {}

    def create(self,…
14 0 Open
A/B testing & experimentation medium

How to Run a Permutation Test in Python

Run a Monte Carlo permutation test to compute a p-value for comparing two group means without parametric assumptions.

permutation-test statistics ab-testing
Python
import random
import statistics

def permutation_test(group_a, group_b, n_permutations=10000, seed=42):
    random.seed(seed)
    combined = group_a + group_b
    observed_diff = abs(statistics.mean(group_a) - statistics.mean(group_b))
    
    count = 0
    n = len(group_a)
    for _ in range(n_permutations):
       …
15 0 Open
Database scaling & optimization medium

Mock CQRS Read/Write Split in Python

Separate order mutations from queries using a read model and write model to mock CQRS-style separation of concerns.

cqrs read-write dataclass
Python
from dataclasses import dataclass, field
from typing import List, Dict


@dataclass
class Order:
    id: int
    amount: float
    status: str = "pending"


class OrderWriteModel:
    """Handles all mutations (writes) to orders."""

    def __init__(self):
        self._orders: Dict[int, Order] = {}
        self._next…
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.