Reference library

Python Code Samples

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

22 matches
Lists & loops easy

Symmetric difference between two lists in Python

Find elements present in exactly one of two lists, preserving original order, with a simple Python function.

lists sets symmetric-difference
Python
def symmetric_difference(list1, list2):
    """
    Return the symmetric difference of two lists.
    Elements present in exactly one of the lists, preserving order.
    """
    set1 = set(list1)
    set2 = set(list2)
    
    # Elements in list1 but not in list2
    diff1 = [x for x in list1 if x not in set2]
    # E…
14 0 Open
OOP & classes easy

How to Call a Parent Class __init__ with super() in Python

Shows how to chain __init__ calls through a class hierarchy using super(), so each class sets its own attributes while reusing the parent's initialization logic.

oop inheritance super
Python
class Animal:
    def __init__(self, name, species):
        self.name = name
        self.species = species
        print(f"Animal init: {self.name}, {self.species}")

class Mammal(Animal):
    def __init__(self, name, species, fur_color):
        super().__init__(name, species)
        self.fur_color = fur_color
   …
13 0 Open
Comprehensions & generators easy

How to Close a Generator and Handle GeneratorExit in Python

This Python code demonstrates how to explicitly close a generator using the close() method and handle the GeneratorExit exception through a finally block to run cleanup logic.

generators generator-exit close
Python
def countdown(n):
    try:
        while n > 0:
            yield n
            n -= 1
    finally:
        print(f"Generator closed after countdown completed")


if __name__ == "__main__":
    gen = countdown(5)
    print(next(gen))
    print(next(gen))
    gen.close()
    print("Generator closed explicitly")
12 0 Open
Modern tooling easy

How to Mock Commitizen Version Bump in Python

Simulate commitizen's version bump logic and mock the subprocess call to avoid real execution in tests.

commitizen mock subprocess
Python
import subprocess
from unittest.mock import patch, MagicMock


def bump_version(current_version: str, increment: str = "patch") -> str:
    """Simulate commitizen's version bump logic."""
    major, minor, patch = map(int, current_version.split("."))
    if increment == "major":
        major += 1
        minor = 0
  …
15 0 Open
Modern tooling easy

How to Mock setuptools_scm get_version in Python

This code demonstrates how to mock setuptools_scm.get_version in Python using unittest.mock.patch to test version retrieval logic without installing or relying on the actual package.

setuptools-scm mock unittest
Python
```python
from unittest.mock import patch

def get_version_from_scm():
    try:
        import setuptools_scm
        return setuptools_scm.get_version()
    except (ImportError, LookupError):
        return None

if __name__ == "__main__":
    with patch("setuptools_scm.get_version", return_value="1.2.3"):
        pr…
14 0 Open
Concurrency & performance easy

How to Time Code Performance with timeit in Python

Benchmark two implementations of the same logic using Python's timeit module and compare their execution speeds.

timeit performance benchmark
Python
import timeit

# Implementation 1: Using a list comprehension
def list_comprehension_squares(n):
    return [i ** 2 for i in range(n)]

# Implementation 2: Using a for loop with append
def loop_squares(n):
    result = []
    for i in range(n):
        result.append(i ** 2)
    return result

if __name__ == "__main__"…
12 0 Open
Testing & modern typing easy

How to Merge TypedDicts in Python

Merge two TypedDict dictionaries with type-aware logic using NotRequired, **kwargs unpacking, and safe key updates.

typing typeddict dict
Python
from typing import TypedDict, NotRequired, merge  # hypothetical

class User(TypedDict):
    name: str
    email: NotRequired[str]
    age: NotRequired[int]

def merge_users(base: User, **overrides: User) -> User:
    """Merge two user dicts with typing-aware logic."""
    result: User = dict(base)
    for key, value …
13 0 Open
System design patterns easy

How to Implement the Repository Pattern in Python with an In-Memory Dict

Stores, retrieves, updates, and deletes user records in memory using a Repository abstraction over a plain dict, isolating data access from business logic.

repository-pattern design-patterns in-memory
Python
class UserRepository:
    def __init__(self):
        self._storage = {}
        self._next_id = 1

    def create(self, name, email):
        user_id = self._next_id
        self._next_id += 1
        self._storage[user_id] = {"id": user_id, "name": name, "email": email}
        return self._storage[user_id]

    def…
11 0 Open
System design patterns easy

How to Mock Hexagonal Architecture Ports and Adapters in Python

Mock an email adapter in a hexagonal architecture with unittest.mock to test business logic in isolation.

hexagonal-architecture unittest-mock dependency-injection
Python
from unittest.mock import Mock

class EmailService:
    def send(self, recipient, message):
        raise NotImplementedError

class OrderProcessor:
    def __init__(self, email_service):
        self.email_service = email_service
    
    def process_order(self, order_id, customer_email):
        # Business logic
   …
15 0 Open
System design patterns easy

Python MVC Pattern Example (Model-View-Controller)

A minimal, runnable Model-View-Controller (MVC) example in pure Python that separates data, presentation, and logic.

mvc design-pattern architecture
Python
class Model:
    def __init__(self):
        self.data = {"title": "Initial Title", "content": "Initial Content"}

    def get_data(self):
        return self.data

    def update_data(self, title=None, content=None):
        if title:
            self.data["title"] = title
        if content:
            self.data["c…
15 0 Open
Streaming & messaging easy

How to Implement a Tumbling Window Counter in Python

Count events that fall within a fixed-size sliding time window using a deque and pruning logic.

streaming window aggregation
Python
from collections import deque
import time


class TumblingWindowCounter:
    def __init__(self, window_size_seconds):
        self.window_size = window_size_seconds
        self.window = deque()

    def add_event(self, timestamp):
        self.window.append(timestamp)

    def count(self, current_time):
        while…
14 0 Open
Streaming & messaging easy

How to Mock RabbitMQ Ack Nack Requeue in Python

A mock RabbitMQ channel and consumer that simulates ack, nack, and requeue handling for testing message processing logic without a broker.

rabbitmq testing mock
Python
import json
from collections import deque


class MockChannel:
    def __init__(self):
        self.acked = []
        self.nacked = []
        self.requeued = []

    def basic_ack(self, delivery_tag):
        self.acked.append(delivery_tag)

    def basic_nack(self, delivery_tag, requeue=False):
        self.nacked.…
15 0 Open
Caching & Redis easy

How to implement a token bucket rate limiter in Python

A thread-safe in-memory token bucket rate limiter that tracks per-key tokens with refill logic, including a usage example after a timed refill.

rate-limiting token-bucket threading
Python
import time
import threading

class TokenBucketRateLimiter:
    def __init__(self, capacity, refill_rate):
        self.capacity = capacity
        self.refill_rate = refill_rate
        self.tokens = capacity
        self.last_refill_time = time.time()
        self.lock = threading.Lock()

    def allow_request(self,…
12 0 Open
Caching & Redis easy

Redis INCR DECR Counter Mock in Python

Simulate Redis INCR and DECR commands with a Python class to test counter logic without a live Redis server.

redis counter mock
Python
class RedisCounter:
    def __init__(self):
        self._store = {}

    def incr(self, key: str, amount: int = 1) -> int:
        if key not in self._store:
            self._store[key] = 0
        self._store[key] += amount
        return self._store[key]

    def decr(self, key: str, amount: int = 1) -> int:
     …
16 0 Open
Reliability & rate limiting easy

How to Build a Rate Limiter in Python

A beginner-friendly token bucket rate limiter with retry logic for handling API rate limits in Python.

rate-limiting token-bucket retry
Python
import time
import random

class RateLimiter:
    """Simple token bucket rate limiter for beginners."""
    
    def __init__(self, max_tokens=5, refill_rate=1.0):
        self.max_tokens = max_tokens
        self.tokens = max_tokens
        self.refill_rate = refill_rate  # tokens per second
        self.last_refill …
15 0 Open
Big data & Spark easy

How to Mock Partition Pruning in Python

A dataclass-based mock that filters partitions by year and month to emulate Spark's partition pruning logic.

spark partition dataclass
Python
from dataclasses import dataclass
from typing import List


@dataclass(frozen=True)
class Partition:
    id: int
    year: int
    month: int


class PartitionPruner:
    """Mock partition pruning: only keep partitions that match the filter."""
    def __init__(self, partitions: List[Partition]):
        self._partiti…
15 0 Open
Big data & Spark easy

How to Mock a Socket Stream in Python

Simulate a streaming socket source with a generator to test stream-read and buffering logic without a real network.

socket mock streaming
Python
import socket
import threading
import time

def mock_socket_stream(data_chunks, delay=0.1):
    """Generator that simulates a streaming socket source."""
    for chunk in data_chunks:
        time.sleep(delay)
        yield chunk

def read_stream_socket(stream_gen):
    """Reads from mock stream and prints received ch…
14 0 Open
Database scaling & optimization easy

How to mock directory-based sharding in Python

Simulates distributing files into logical shards using a deterministic hash of each filename, mocking how a database might shard rows across nodes.

sharding hash partitioning
Python
import os
import hashlib
from collections import defaultdict
from pathlib import Path


def get_shard_for_key(key: str, num_shards: int) -> int:
    """Return a deterministic shard index (0..num_shards-1) for a key."""
    digest = hashlib.md5(key.encode('utf-8')).hexdigest()
    return int(digest, 16) % num_shards


…
14 0 Open
Production deployment patterns easy

How to Mock a CI Pipeline with Build, Test, and Deploy Stages in Python

Simulate a three-stage CI pipeline (build, test, deploy) in Python with random pass/fail logic, early exit on failure, and measured stage durations.

ci-cd simulation dataclasses
Python
import time
import random
from dataclasses import dataclass


@dataclass
class StageResult:
    name: str
    status: str
    duration: float


def run_stage(name: str, success_chance: float = 0.9) -> StageResult:
    """Simulate a pipeline stage with random success/failure."""
    start = time.time()
    time.sleep(r…
14 0 Open
Production deployment patterns easy

How to Mock a Container Registry in Python

Build an in-memory container registry mock with push, tag listing, and manifest retrieval logic for testing deployment tooling.

containers testing mocking
Python
import json
from collections import defaultdict


class MockRegistry:
    def __init__(self):
        self.repositories = defaultdict(dict)

    def push_image(self, repo: str, tag: str, layers: list[str]) -> None:
        self.repositories[repo][tag] = {
            "layers": layers,
            "size": sum(len(layer…
14 0 Open
Production deployment patterns easy

How to Mock time.sleep in a Python PreStop Hook

This code simulates a Kubernetes PreStop hook that delays shutdown, then mocks time.sleep to verify the hook logic without real delay.

mocking prestop kubernetes
Python
import subprocess
import sys
import time
from unittest.mock import patch

def pre_stop_hook():
    """Simulate a Kubernetes PreStop hook that sleeps before shutdown."""
    print("PreStop hook started: delaying shutdown")
    time.sleep(3)
    print("PreStop hook completed: ready to shutdown")

if __name__ == "__main_…
14 0 Open
Production deployment patterns easy

How to Roll Back to a Previous Image Tag in Python

A dataclass-based mock registry that tracks image tag history and rolls back to the previous tag, useful for deployment rollback logic.

rollback deployment dataclass
Python
"""Demonstrates a rollback pattern for a Docker-style image tag registry."""

from dataclasses import dataclass, field


@dataclass
class ImageRegistry:
    """A minimal mock registry tracking current tags per image."""

    tags: dict[str, list[str]] = field(default_factory=dict)

    def push(self, image: str, tag: …
13 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.