Reference library

Python Code Samples

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

60 matches
Functions & basics easy

How to Create Generator Functions with yield in Python

Create a memory-efficient generator function using yield to produce a Fibonacci sequence up to a limit.

generator yield fibonacci
Python
def fibonacci_sequence(limit):
    """Generate Fibonacci numbers up to a given limit."""
    a, b = 0, 1
    while a <= limit:
        yield a
        a, b = b, a + b


if __name__ == "__main__":
    fib_gen = fibonacci_sequence(100)
    
    for number in fib_gen:
        print(number, end=" ")
    print()
11 0 Open
Functions & basics easy

How to measure function memory with sys.getsizeof in Python

Measure the memory footprint of Python functions (user-defined and built-in) using sys.getsizeof.

sys getsizeof memory
Python
import sys

def sample_function(a, b, c):
    return a + b - c

def measure_function_memory(func):
    size = sys.getsizeof(func)
    print(f"Memory size of {func.__name__}: {size} bytes")

if __name__ == "__main__":
    measure_function_memory(sample_function)
    measure_function_memory(print)
    measure_function_m…
13 0 Open
Functions & basics easy

Profile Python functions with cProfile

Profile a Python program with cProfile, capture the stats in memory, and print a sorted performance report.

cprofile performance profiling
Python
import cProfile
import pstats
import io


def slow_function():
    total = 0
    for i in range(100000):
        total += i ** 2
    return total


def medium_function():
    return sum(range(10000))


def fast_function():
    return sum(range(100))


def main():
    result1 = slow_function()
    result2 = medium_func…
11 0 Open
Files & data easy

Compress and Extract ZIP Files Programmatically in Python

Create a ZIP archive with in-memory files and extract its contents to a directory using Python's stdlib zipfile and pathlib modules.

zip compression file-io
Python
import zipfile
from pathlib import Path
import tempfile
import os

def create_sample_zip(zip_path: str, files: dict) -> None:
    """Create a ZIP file containing the given files (name -> content mapping)."""
    with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
        for filename, content in files.ite…
99 0 Open
Files & data easy

Create an In-Memory SQLite Table and Query It in Python

This code creates an in-memory SQLite database, defines an employees table, inserts sample rows, and runs a filtered query with sorted results.

sqlite in-memory database
Python
import sqlite3

conn = sqlite3.connect(":memory:")
cursor = conn.cursor()

cursor.execute("""
    CREATE TABLE employees (
        id INTEGER PRIMARY KEY,
        name TEXT NOT NULL,
        department TEXT NOT NULL,
        salary REAL
    )
""")

employees = [
    (1, "Alice", "Engineering", 95000),
    (2, "Bob", "…
11 0 Open
Files & data easy

How to Compress a String to Gzip Bytes in Python

Compress a string into gzip-compressed bytes entirely in memory using the standard library gzip module.

gzip compression bytes
Python
import gzip

def compress_to_gzip_bytes(data: str, encoding: str = "utf-8") -> bytes:
    """Compress a string to gzip-compressed bytes in memory."""
    return gzip.compress(data.encode(encoding))

if __name__ == "__main__":
    original = "Hello, world! " * 10
    compressed = compress_to_gzip_bytes(original)
    pr…
13 0 Open
Files & data easy

How to Serialize a Python Object to Pickle Bytes in Memory

Serialize a Python object to pickle bytes in memory with pickle.dumps, then deserialize it back with pickle.loads and verify the roundtrip.

pickle serialization bytes
Python
import pickle

class Person:
    def __init__(self, name, age, skills):
        self.name = name
        self.age = age
        self.skills = skills

def main():
    person = Person("Alice", 30, ["Python", "SQL", "Docker"])
    
    # Serialize to bytes in memory
    pickle_bytes = pickle.dumps(person)
    
    print(…
16 0 Open
Files & data easy

How to Write Simple XML Documents with ElementTree in Python

Create well-structured XML documents in memory using Python's built-in ElementTree module, complete with nested elements, attributes, and text content.

xml elementtree serialization
Python
import xml.etree.ElementTree as ET

def create_xml_document():
    # Create root element
    root = ET.Element("catalog")
    
    # Create a book element with attributes and children
    book1 = ET.SubElement(root, "book", id="bk101")
    ET.SubElement(book1, "author").text = "Gambardella, Matthew"
    ET.SubElement(…
13 0 Open
OOP & classes easy

How to Build an In-Memory CRUD Repository Class in Python

Define a Python Repository class that stores objects in a dictionary and supports create, read, update, delete, and list operations.

repository crud oop
Python
class Repository:
    def __init__(self):
        self._data = {}

    def create(self, key, value):
        self._data[key] = value
        return key

    def read(self, key):
        return self._data.get(key)

    def update(self, key, value):
        if key not in self._data:
            raise KeyError(f"Key '{ke…
14 0 Open
OOP & classes easy

Slots Class: How to Reduce Memory Usage in Python

Use __slots__ to prevent dynamic attribute creation and reduce per-instance memory overhead, while keeping methods intact.

memory slots class
Python
class SlotsDemo:
    __slots__ = ("name", "age", "email")

    def __init__(self, name, age, email):
        self.name = name
        self.age = age
        self.email = email

    def describe(self):
        return f"{self.name}, {self.age}, {self.email}"

if __name__ == "__main__":
    instance = SlotsDemo("Alice", …
12 0 Open
Comprehensions & generators easy

Build a lazy generator to read file lines in Python

Create a generator function that yields file lines one at a time, avoiding loading the entire file into memory, and demonstrate its lazy processing.

generator file-io lazy
Python
def lazy_lines(filepath):
    """Yield lines from a file one at a time without loading the whole file into memory."""
    with open(filepath, 'r', encoding='utf-8') as file:
        for line in file:
            yield line.rstrip('\n')


if __name__ == "__main__":
    # Create a sample file to demonstrate
    sample_c…
14 0 Open
Comprehensions & generators easy

Generator Function to Yield an Infinite Counter in Python

This code demonstrates a generator function that yields an infinite sequence of integers starting from a given value, allowing lazy, memory-efficient iteration.

generators infinite sequences yield
Python
def infinite_counter(start=0):
    count = start
    while True:
        yield count
        count += 1

if __name__ == "__main__":
    counter = infinite_counter(5)
    for _ in range(5):
        print(next(counter))
14 0 Open
Comprehensions & generators easy

How to Create a Pairwise Generator with zip and tee in Python

Build a memory-efficient generator that yields successive overlapping pairs from any iterable using zip and tee.

itertools generators zip
Python
from itertools import tee


def pairwise(iterable):
    """Yield successive overlapping pairs from iterable."""
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)


if __name__ == "__main__":
    values = [1, 2, 3, 4, 5]
    print(list(pairwise(values)))
    print(list(pairwise("hello")))
15 0 Open
Comprehensions & generators easy

How to Create an Infinite Arithmetic Sequence Generator in Python

Build a memory-efficient generator that yields an infinite arithmetic progression and extract the first N values with list comprehension.

generators yield infinite-sequences
Python
"""Count generator infinite arithmetic progression"""


def arithmetic_counter(start=0, step=1):
    """Generate an infinite arithmetic sequence."""
    current = start
    while True:
        yield current
        current += step


if __name__ == "__main__":
    counter = arithmetic_counter(1, 3)
    result = [next(c…
14 0 Open
Comprehensions & generators easy

How to Generate Fibonacci Numbers in Python Without Recursion

Build an efficient infinite Fibonacci sequence using a generator function with O(1) memory and no recursion overhead.

generators fibonacci iteration
Python
def fib(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

if __name__ == "__main__":
    count = 10
    result = list(fib(count))
    print(result)
15 0 Open
Comprehensions & generators easy

Memory efficient map over large file in Python

A generator-based streaming map that processes a large file line by line without loading the whole file into memory.

generator file-io streaming
Python
import sys

def process_lines(file_path):
    """Memory-efficient map over a large file: yields processed lines."""
    with open(file_path, 'r') as f:
        for line in f:
            # Example mapping: strip whitespace and uppercase
            yield line.strip().upper()

if __name__ == "__main__":
    # Use a sma…
12 0 Open
Comprehensions & generators easy

Sum of Squares with a Generator Expression in Python

This code computes the sum of squares of integers from 1 to n using a generator expression, demonstrating a memory-efficient and concise way to aggregate a sequence.

generator sum squares
Python
def sum_of_squares(n):
    return sum(x * x for x in range(1, n + 1))

if __name__ == "__main__":
    print(f"Sum of squares from 1 to 5: {sum_of_squares(5)}")
    print(f"Sum of squares from 1 to 10: {sum_of_squares(10)}")
14 0 Open
AI & LLM integration patterns easy

Cache LLM Completions by Hashing the Prompt in Python

A simple in-memory cache that stores LLM completions keyed by a SHA-256 hash of the prompt to avoid recomputing identical requests.

llm caching hashing
Python
import hashlib
import json

class PromptCache:
    def __init__(self):
        self.cache = {}

    def _hash_prompt(self, prompt: str) -> str:
        return hashlib.sha256(prompt.encode("utf-8")).hexdigest()

    def get(self, prompt: str) -> str | None:
        key = self._hash_prompt(prompt)
        return self.ca…
14 0 Open
AI & LLM integration patterns easy

How to Build an Agent Loop with Plan, Act, Observe in Python

Implements a simple plan-act-observe loop that an AI agent uses to iteratively complete a task in an environment while storing observations in memory.

agents loop llm
Python
class Agent:
    def __init__(self, name):
        self.name = name
        self.memory = {}

    def plan(self, task):
        return f"Plan for {task}: step 1, step 2, step 3"

    def act(self, plan, environment):
        return f"Executing {plan} in {environment}"

    def observe(self, action_result):
        sel…
17 0 Open
AI & LLM integration patterns easy

How to Build an Entity Memory Dict to Store Facts in Python

Store and recall facts about entities using nested dictionaries with remember, recall, and forget functions in Python.

memory dict nested-dict
Python
facts = {}

def remember(entity, attribute, value):
    if entity not in facts:
        facts[entity] = {}
    facts[entity][attribute] = value

def recall(entity, attribute):
    return facts.get(entity, {}).get(attribute, None)

def forget(entity, attribute=None):
    if attribute is None:
        facts.pop(entity, …
12 0 Open
AI & LLM integration patterns easy

How to Build an In-Memory Vector Store in Python

Build a lightweight in-memory vector store using a Python dict and cosine similarity for fast nearest-neighbor searches.

vector-store cosine-similarity embeddings
Python
import math
from typing import Dict, List, Optional


class InMemoryVectorStore:
    def __init__(self) -> None:
        self.vectors: Dict[str, List[float]] = {}
        self.index: Dict[str, List[str]] = {}  # query -> list of ids sorted by similarity

    def add(self, vector_id: str, vector: List[float]) -> None:
…
12 0 Open
AI & LLM integration patterns easy

How to Keep Last K Turns in a Memory Buffer in Python

A TurnBuffer class using deque with maxlen to keep only the most recent k conversation turns in memory for LLM context.

deque llm-context memory-buffer
Python
from collections import deque

class TurnBuffer:
    def __init__(self, k):
        self.k = k
        self.turns = deque(maxlen=k)

    def add(self, turn):
        self.turns.append(turn)

    def last_k(self):
        return list(self.turns)


if __name__ == "__main__":
    buffer = TurnBuffer(3)
    buffer.add("tu…
14 0 Open
Automation & scripting easy

How to Monitor Process RSS Memory in Python

Poll the VmRSS field from /proc/PID/status to watch a process's resident memory and alert on growth.

memory monitoring process
Python
import os
import time
import subprocess
import sys

def get_rss_mb(pid):
    """Return RSS memory in MB for a given process ID."""
    try:
        with open(f"/proc/{pid}/status", "r") as f:
            for line in f:
                if line.startswith("VmRSS:"):
                    return int(line.split()[1]) / 1024…
13 0 Open
Data pipelines & processing easy

Implement Exactly-Once Transaction Log in Python

A mock transaction log that deduplicates transaction IDs so each is recorded only once, with a dataclass for records and simple in-memory storage.

transactions deduplication dataclass
Python
from dataclasses import dataclass
from typing import Dict, Optional


@dataclass
class TxnRecord:
    txn_id: str
    status: str


class ExactlyOnceTxnLog:
    def __init__(self) -> None:
        self._log: Dict[str, TxnRecord] = {}
        self._processed_ids: set = set()

    def record(self, txn_id: str, status: s…
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.