Reference library

Python Code Samples

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

8 matches
OOP & classes medium

How to Use __slots__ in Python Classes for Memory Efficiency

Defines classes with __slots__ to prevent dynamic attribute creation and reduce memory usage, including inheritance with additional slots.

slots oop memory
Python
```python
class Person:
    __slots__ = ("name", "age")

    def __init__(self, name: str, age: int):
        self.name = name
        self.age = age

    def greet(self) -> str:
        return f"Hi, I'm {self.name} and I'm {self.age} years old."


class Employee(Person):
    __slots__ = ("role",)

    def __init__(se…
13 0 Open
Concurrency & performance medium

How to Reduce Instance Memory with __slots__ in Python

Demonstrates that classes with __slots__ use less memory per instance than regular classes because they skip the instance __dict__.

__slots__ memory performance
Python
class SlottedPoint:
    __slots__ = ('x', 'y', 'z')

    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z


class RegularPoint:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z


if __name__ == "__main__":
    regular = RegularPoint(1, 2, 3)…
11 0 Open
Caching & Redis medium

How to Build a Bloom Filter to Reduce Cache Misses in Python

Implement a probabilistic Bloom filter in Python that lets a cache quickly determine which keys are definitely not present, reducing expensive source lookups on cache misses.

bloom-filter caching probabilistic
Python
import hashlib
import random

class BloomFilter:
    def __init__(self, size=100, num_hashes=3):
        self.size = size
        self.num_hashes = num_hashes
        self.bit_array = [0] * size

    def _hashes(self, item):
        result = []
        for i in range(self.num_hashes):
            hash_value = int(hash…
14 0 Open
Caching & Redis medium

How to Implement a Negative Cache with TTL in Python

This code provides a TTL mock cache that stores negative results (cache misses) for a short time to reduce repeated lookups of missing keys.

cache ttl negative-cache
Python
from time import time, sleep

class TTLMockCache:
    def __init__(self, ttl_seconds=5):
        self.ttl = ttl_seconds
        self.store = {}
        self.negative_cache = {}

    def get(self, key):
        now = time()
        if key in self.store:
            value, expires_at = self.store[key]
            if exp…
13 0 Open
Big data & Spark medium

How to Implement a Mock MapReduce for Word Count in Python

Simulates a MapReduce word count pipeline with mapper, shuffle, and reducer phases using Python dicts and standard library modules.

mapreduce word-count big-data
Python
from collections import defaultdict
import re

def mapper(text):
    """Split text into words and emit (word, 1) pairs."""
    words = re.findall(r'\b\w+\b', text.lower())
    return [(word, 1) for word in words]

def reducer(pairs):
    """Group word-count pairs and sum counts."""
    counts = defaultdict(int)
    fo…
15 0 Open
Big data & Spark medium

How to Simulate a MapReduce Mock with Combine Phase in Python

Simulates a MapReduce pipeline with a combiner that aggregates local counts per reducer to reduce network and compute overhead.

mapreduce combiner hadoop
Python
from collections import defaultdict

def map_phase(lines):
    intermediate = defaultdict(list)
    for line in lines:
        for word in line.strip().lower().split():
            intermediate[word].append(1)
    return dict(intermediate)

def combine_phase(intermediate, num_reducers=3):
    combined = defaultdict(li…
14 0 Open
A/B testing & experimentation medium

How to Compute CUPED Variance Reduction in Python

Implement CUPED in Python to reduce variance of A/B test treatment effect estimates using pre-experiment covariates.

cuped ab-testing variance-reduction
Python
import numpy as np

def compute_cuped_reduction(control, variant, covariate):
    """
    Compute variance reduction using CUPED (Controlled Experiment with
    Pre-Experiment Data). Uses pre-experiment covariate values to
    reduce variance of the treatment effect estimate.
    """
    control = np.asarray(control, …
16 0 Open
Database scaling & optimization medium

How to Eager Load with JOIN to Reduce N+1 Queries in Python

Demonstrates eager loading with a SQL JOIN to reduce N+1 query patterns down to a single database call when fetching related data.

eager-loading n-plus-1 join
Python
import sqlite3


def eager_load_join_reduce(mock_db_path=":memory:"):
    """Demonstrate eager loading where joins reduce query count from N+1 to 1."""
    conn = sqlite3.connect(mock_db_path)
    cursor = conn.cursor()
    cursor.executescript(
        """
        CREATE TABLE authors (id INTEGER PRIMARY KEY, name TE…
16 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.