Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

66 matches
Concurrency & performance medium

How to Use ProcessPoolExecutor for CPU Parallel Map in Python

Run a function over a sequence of inputs in parallel across multiple CPU cores with ProcessPoolExecutor.map.

concurrency processpoolexecutor parallelism
Python
from concurrent.futures import ProcessPoolExecutor
import math

def compute_square(num):
    return num * num

def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(math.sqrt(n)) + 1):
        if n % i == 0:
            return False
    return True

if __name__ == "__main__":
    numbers = rang…
11 0 Open
Concurrency & performance medium

How to Use Thread Pool Executor map for IO-Bound Tasks in Python

Run multiple I/O-bound tasks concurrently with ThreadPoolExecutor map and collect their results in order.

threadpool concurrency io-bound
Python
import time
from concurrent.futures import ThreadPoolExecutor

def io_bound_task(task_id: int) -> str:
    time.sleep(0.2)  # mock I/O wait
    return f"Task {task_id} completed"

def main() -> None:
    task_ids = [1, 2, 3, 4, 5]
    with ThreadPoolExecutor(max_workers=3) as executor:
        results = list(executor.…
12 0 Open
Concurrency & performance easy

How to Use ThreadPoolExecutor and ProcessPoolExecutor in Python

Compares ThreadPoolExecutor and ProcessPoolExecutor by running CPU-bound and I/O-tolerant tasks over a large list, printing elapsed times and first results.

concurrency threadpool processpool
Python
import time
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
import math

numbers = list(range(1, 1000001))


def compute_square(n):
    return n * n


def compute_sqrt(n):
    return math.sqrt(n)


def run_executor(executor, func, data):
    start = time.perf_counter()
    results = list(executo…
15 0 Open
Concurrency & performance medium

How to Use ThreadPoolExecutor for Concurrent Tasks in Python

Compare sequential execution with ThreadPoolExecutor for I/O-bound tasks, measuring speedup and timing with perf_counter.

concurrency threadpool performance
Python
import time
import threading
from concurrent.futures import ThreadPoolExecutor


def fetch_data(index):
    """Simulate a synchronous data fetch."""
    time.sleep(0.1)
    return f"data-{index}"


def run_sequential(total=10):
    """Run tasks one after another."""
    start = time.perf_counter()
    results = [fetch…
14 0 Open
Concurrency & performance easy

How to Use ThreadPoolExecutor in Python for Parallel Processing

Use ThreadPoolExecutor with executor.map to run a function over many inputs concurrently and collect ordered results.

concurrency threadpoolexecutor parallel
Python
def worker(item):
    return item * item

if __name__ == "__main__":
    from concurrent.futures import ThreadPoolExecutor
    numbers = list(range(1, 11))
    with ThreadPoolExecutor(max_workers=4) as executor:
        results = list(executor.map(worker, numbers))
    print("Input:  ", numbers)
    print("Results:", …
13 0 Open
Concurrency & performance easy

How to Use ThreadPoolExecutor.submit() in Python

Exécute des fonctions en parallèle avec ThreadPoolExecutor.submit(), récupère les résultats avec future.result(), et traite plusieurs tâches simultanément en Python standard.

concurrency threads threadpoolexecutor
Python
from concurrent.futures import ThreadPoolExecutor
import time

def square(n):
    time.sleep(0.1)  # Simulate work
    return n * n

if __name__ == "__main__":
    with ThreadPoolExecutor(max_workers=3) as executor:
        future = executor.submit(square, 5)
        result = future.result()
        print(f"Result: {r…
12 0 Open
Concurrency & performance medium

How to Use as_completed to Process Futures in Order of Completion

Submit multiple tasks to a ThreadPoolExecutor and process each result as soon as it finishes using as_completed.

concurrency threads futures
Python
from concurrent.futures import ThreadPoolExecutor, as_completed
import time


def fetch_data(item_id):
    time.sleep(1)
    return f"item-{item_id}"


def main():
    with ThreadPoolExecutor(max_workers=3) as executor:
        future_map = {executor.submit(fetch_data, i): i for i in range(1, 6)}
        for future in…
14 0 Open
Concurrency & performance medium

How to Use asyncio Lock to Protect a Shared Counter in Python

This code demonstrates how to use an asyncio.Lock to safely increment a shared counter from multiple concurrent coroutines.

asyncio lock concurrency
Python
import asyncio

async def increment(counter, lock, increments):
    for _ in range(increments):
        async with lock:
            counter[0] += 1

async def main():
    counter = [0]
    lock = asyncio.Lock()
    tasks = [
        increment(counter, lock, 1000)
        for _ in range(5)
    ]
    await asyncio.gath…
16 0 Open
Concurrency & performance medium

How to Use multiprocessing Pool map and starmap in Python

Parallelize functions over iterables with Pool.map, and unpack multiple arguments via Pool.starmap.

multiprocessing parallelism pool
Python
from multiprocessing import Pool


def square(x):
    return x * x


def add_and_multiply(a, b, c):
    return (a + b) * c


if __name__ == "__main__":
    numbers = [1, 2, 3, 4, 5]
    with Pool(processes=2) as pool:
        squares = pool.map(square, numbers)
        print(f"squares: {squares}")

        starmap_arg…
14 0 Open
Concurrency & performance easy

How to Use pool.map for CPU-Bound Tasks in Python

Distribute CPU-intensive functions across processes with multiprocessing.Pool.map and measure the performance gain.

multiprocessing pool cpu-bound
Python
from multiprocessing import Pool
import time

def cpu_bound_task(n):
    """Mock CPU-bound work: compute sum of squares."""
    total = 0
    for i in range(n):
        total += i * i
    return total

if __name__ == "__main__":
    numbers = [10_000_000, 12_000_000, 8_000_000, 15_000_000]

    start = time.perf_count…
11 0 Open
Concurrency & performance easy

How to Use threading.Lock to Synchronize a Counter in Python

Safely increment a shared counter across multiple threads using threading.Lock as a mutex to prevent race conditions.

threading lock mutex
Python
import threading

counter = 0
lock = threading.Lock()

def increment():
    global counter
    for _ in range(100000):
        with lock:
            counter += 1

threads = [threading.Thread(target=increment) for _ in range(5)]
for t in threads:
    t.start()
for t in threads:
    t.join()

print(f"Final counter valu…
14 0 Open
Concurrency & performance medium

How to Use threading.RLock in Python

Demonstrates threading.RLock, a reentrant lock that allows the same thread to acquire it multiple times without deadlocking — essential for recursive functions sharing state across threads.

threading rlock concurrency
Python
import threading
import time

lock = threading.RLock()
shared_counter = 0

def recursive_increment(value, depth):
    global shared_counter
    with lock:
        shared_counter += 1
        print(f"Depth {depth}: counter = {shared_counter}")
        if depth > 1:
            recursive_increment(value, depth - 1)

def…
14 0 Open
Concurrency & performance medium

How to Use threading.local for Per-Thread Data in Python

Use threading.local to keep thread-specific data — each thread gets its own copy of the attribute, so values don't leak between threads.

threading thread-local concurrency
Python
import threading
import time

local_storage = threading.local()

def worker(name):
    local_storage.name = name
    time.sleep(0.1)
    print(f"Thread {threading.current_thread().name}: {local_storage.name}")

if __name__ == "__main__":
    threads = []
    for i in range(3):
        t = threading.Thread(target=worke…
14 0 Open
Concurrency & performance easy

How to Use uvloop Faster Event Loop

Install uvloop at startup to replace asyncio's default event loop with a faster libuv-based one, with a graceful fallback when it's unavailable.

uvloop asyncio event-loop
Python
import asyncio
try:
    import uvloop
    uvloop.install()
    USING_UVLOOP = True
except ImportError:
    USING_UVLOOP = False


async def fetch_data(index):
    await asyncio.sleep(0.01)
    return f"data-{index}"


async def main():
    tasks = [fetch_data(i) for i in range(10)]
    results = await asyncio.gather(*…
14 0 Open
Concurrency & performance easy

How to Validate Data with ThreadPoolExecutor in Python

This code shows how to validate a list of numbers concurrently using ThreadPoolExecutor, dramatically speeding up slow validation tasks by running them in parallel threads.

concurrency threadpool validation
Python
import time
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass


@dataclass
class Result:
    is_valid: bool
    value: int


def validate(value: int) -> Result:
    time.sleep(0.1)  # simulate slow validation (API call, DB check)
    return Result(is_valid=0 < value < 100, value=value…
11 0 Open
Concurrency & performance easy

How to set a timeout with asyncio.wait_for in Python

Use asyncio.wait_for to bound an async function with a timeout, catching TimeoutError when it exceeds the limit.

asyncio timeout concurrency
Python
import asyncio

async def slow_task():
    await asyncio.sleep(3)
    return "finished"

async def main():
    try:
        result = await asyncio.wait_for(slow_task(), timeout=1)
        print(result)
    except asyncio.TimeoutError:
        print("Task timed out")

if __name__ == "__main__":
    asyncio.run(main())
13 0 Open
Concurrency & performance easy

How to spawn multiple worker processes in Python with multiprocessing.Process

Spawns three separate worker processes using multiprocessing.Process, runs them concurrently, and waits for all to finish before printing a completion message.

multiprocessing parallel concurrency
Python
import multiprocessing
import time

def worker(name):
    print(f"Worker {name} started")
    time.sleep(1)
    print(f"Worker {name} finished")
    return name

if __name__ == "__main__":
    processes = []
    for i in range(3):
        p = multiprocessing.Process(target=worker, args=(i,))
        processes.append(p…
14 0 Open
Concurrency & performance easy

How to start, join, and make daemon threads in Python

Starts one daemon and one non-daemon thread, joins the non-daemon thread, and shows how daemon threads exit when the main program ends.

threading daemon join
Python
import threading
import time
import logging

logging.basicConfig(level=logging.INFO, format="%(threadName)s: %(message)s")

def worker(name, delay):
    for i in range(3):
        time.sleep(delay)
        logging.info(f"{name} step {i}")

if __name__ == "__main__":
    daemon_thread = threading.Thread(
        target…
13 0 Open
Concurrency & performance easy

How to use ThreadPoolExecutor for concurrent tasks in Python

Run blocking functions in parallel with ThreadPoolExecutor and as_completed, cutting total runtime from 5 sequential sleeps to about 1 second.

concurrency threadpoolexecutor parallel
Python
import time
from concurrent.futures import ThreadPoolExecutor, as_completed


def fetch_data(item):
    """Simulate a slow operation with a fixed delay."""
    time.sleep(0.2)
    return item * 2


def main():
    items = [1, 2, 3, 4, 5]
    start = time.perf_counter()

    with ThreadPoolExecutor(max_workers=3) as ex…
14 0 Open
Concurrency & performance medium

Limit Concurrency with asyncio.Semaphore in Python

Use asyncio.Semaphore to cap how many async tasks run at once, throttling a batch of coroutines to a set concurrency limit.

asyncio concurrency semaphore
Python
import asyncio
import random


async def fetch_data(i: int, semaphore: asyncio.Semaphore) -> str:
    async with semaphore:
        print(f"Task {i} starts")
        await asyncio.sleep(random.uniform(0.1, 0.5))
        print(f"Task {i} finishes")
        return f"Result {i}"


async def main() -> None:
    semaphore …
13 0 Open
Concurrency & performance medium

Mocking Trio's open_nursery and spawn with asyncio.TaskGroup

Show how to mock Trio's nursery pattern using Python's asyncio.TaskGroup to simulate task spawning and completion.

asyncio taskgroup concurrency
Python
import asyncio

class MockSpawner:
    async def spawn(self, nursery):
        print("Spawning mock task...")
        await asyncio.sleep(1)
        print("Mock task completed")

async def open_nursery():
    async with asyncio.TaskGroup() as nursery:
        mock = MockSpawner()
        nursery.create_task(mock.spawn…
14 0 Open
Concurrency & performance easy

Run Background Tasks with asyncio.create_task in Python

Create background tasks in an asyncio event loop with asyncio.create_task and run them concurrently using asyncio.gather.

asyncio async concurrency
Python
import asyncio
import time

async def background_worker(name, duration):
    """Simulates a long-running background task."""
    print(f"{name} started at t={time.monotonic():.1f}")
    await asyncio.sleep(duration)
    print(f"{name} finished at t={time.monotonic():.1f}")

async def main():
    print(f"Main starting …
13 0 Open
Concurrency & performance easy

Synchronize Threads with a Barrier in Python

Demonstrates using threading.Barrier to synchronize multiple threads at phase boundaries, ensuring all workers wait for each other before proceeding.

threading synchronization barrier
Python
import threading
import time
from random import randint

def worker(barrier, worker_id):
    for phase in range(3):
        time.sleep(randint(1, 3))
        print(f"Worker {worker_id} finished phase {phase} at {time.time():.2f}")
        barrier.wait()
    print(f"Worker {worker_id}: all phases complete")

if __name_…
14 0 Open
Concurrency & performance medium

Thread Pool Map for IO Bound Tasks in Python

Run IO-bound mock tasks concurrently with ThreadPoolExecutor.map and measure total elapsed time in Python.

threading concurrency threadpoolexecutor
Python
import concurrent.futures
import time
from pathlib import Path

def mock_io_task(filename):
    """Simulate an IO-bound task by creating a small file and measuring its latency."""
    path = Path(filename)
    path.write_text("data")
    time.sleep(0.1)  # Simulate slow disk/network
    return f"{filename} written in …
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.