Reference library

Python Code Samples

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

16 matches
Automation & scripting easy

Stress CPU Threads with a Mock Compute in Python

Simulates CPU-intensive work across multiple threads to test how Python schedules parallel compute.

threading cpu-stress parallelism
Python
import threading
import time


def stress_cpu(iterations: int):
    result = 0
    for i in range(iterations):
        result += i * i % 1000
    return result


def run_mock_stress(thread_count: int, iterations: int):
    threads = []
    for tid in range(thread_count):
        t = threading.Thread(target=lambda: str…
12 0 Open
Data pipelines & processing easy

Parallel Extract Multiple Sources with Threads in Python

Extract data from multiple sources in parallel using ThreadPoolExecutor and verify results match sequential processing.

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

def extract_from_source(source):
    """Simulate extracting data from a source."""
    return f"Data from {source}"

def main():
    sources = ["source_a", "source_b", "source_c", "source_d"]
    
    # Sequential extraction for comparison
    sequent…
14 0 Open
Concurrency & performance medium

How to Demonstrate the GIL with Python Threads vs Processes

Measure and compare wall-clock time for CPU-bound work using Python threads (limited by the GIL) versus multiprocessing (which bypasses the GIL).

gil threading multiprocessing
Python
import threading
import multiprocessing
import time
import os


def cpu_heavy(n):
    return sum(i * i for i in range(n))


def run_threads(n):
    threads = [threading.Thread(target=cpu_heavy, args=(n,)) for _ in range(2)]
    start = time.perf_counter()
    for t in threads:
        t.start()
    for t in threads:
 …
11 0 Open
Concurrency & performance medium

How to Pause and Resume Threads with threading.Event in Python

Use threading.Event to pause and resume worker threads in Python, controlling execution flow with set and clear methods.

threading events concurrency
Python
import threading
import time

workers = []

def worker(name, event):
    for i in range(10):
        event.wait()
        print(f"{name} step {i}")
        time.sleep(0.1)

def pause_worker(name):
    global pause_event
    for w in workers:
        if w.name == name:
            pause_event.clear()
            print(…
10 0 Open
Concurrency & performance medium

How to Speed Up Downloads with ThreadPoolExecutor in Python

Compare sequential and thread-pool download loops to measure real speedup when I/O s bound.

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

def download_file(file_id):
    """Simulate fetching a file by sleeping briefly."""
    time.sleep(0.2)  # pretend network latency
    return f"file_{file_id}"

def sequential_downloads(num_files):
    """Process files one at a time."""
  …
13 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 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 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 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

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 easy

Thread-Safe Producer Consumer Queue in Python

A producer-consumer pattern using thread-safe queue.Queue with two threads, demonstrating safe communication and synchronized task completion.

queue threading producer-consumer
Python
import queue
import threading
import time
import random


def producer(q, item_count):
    for i in range(item_count):
        item = random.randint(1, 100)
        q.put(item)
        print(f"Producer added: {item}")
        time.sleep(0.1)


def consumer(q):
    while True:
        try:
            item = q.get(time…
12 0 Open
System design patterns medium

How to Limit Concurrent Requests with a Semaphore in Python

Use threading.Semaphore with a ThreadPoolExecutor to cap how many worker threads run simultaneously, preventing resource overload.

concurrency semaphore threading
Python
import threading
import time
from concurrent.futures import ThreadPoolExecutor

def worker(name, semaphore, results):
    with semaphore:
        results.append(f"start {name}")
        time.sleep(0.5)  # simulate async work
        results.append(f"done {name}")

def main():
    sem = threading.Semaphore(2)  # max 2 …
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.