Reference library

Python Code Samples

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

10 matches
Functions & basics easy

Benchmark list append vs comprehension in Python

This micro-benchmark compares the speed of building a list with a for loop and append versus a list comprehension, using the timeit module to get precise timings.

timeit benchmark performance
Python
import timeit

# Build a list of the first 1,000,000 integers using append in a loop
def append_loop(n=1_000_000):
    result = []
    for i in range(n):
        result.append(i)
    return result

# Build the same list using a list comprehension
def comprehension(n=1_000_000):
    return [i for i in range(n)]

if __n…
13 0 Open
Functions & basics easy

How to Compare Two Implementations with timeit in Python

Measure and compare the execution time of iterative vs recursive factorial functions using the timeit module.

timeit benchmark performance
Python
import timeit

def factorial_iterative(n):
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result

def factorial_recursive(n):
    if n == 0:
        return 1
    return n * factorial_recursive(n - 1)

if __name__ == "__main__":
    n = 10
    iterations = 10000

    iterative_time = timeit…
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
Automation & scripting easy

Benchmark Disk Write Speed in Python with tempfile

Benchmark raw disk write performance by writing a temporary file in 1MB chunks and measuring throughput in MB/s.

benchmark tempfile performance
Python
import os
import tempfile
import time

def benchmark_write(size_mb=50):
    size_bytes = size_mb * 1024 * 1024
    chunk = b'x' * 1024 * 1024  # 1 MB chunk

    with tempfile.NamedTemporaryFile(delete=True) as tmp:
        start = time.perf_counter()
        written = 0
        while written < size_bytes:
            …
11 0 Open
Automation & scripting medium

Benchmark File Read and Write Speed in Python

Measures file write and read throughput in MB/s by writing and reading a temporary file of a given size.

benchmark file-io performance
Python
import os
import time
import tempfile

def benchmark_write(file_path, size_mb=100):
    data = b'x' * (1024 * 1024)  # 1 MB block
    start = time.perf_counter()
    with open(file_path, 'wb') as f:
        for _ in range(size_mb):
            f.write(data)
    elapsed = time.perf_counter() - start
    return size_mb …
43 0 Open
Concurrency & performance medium

Benchmark list.append vs deque.append in Python

Measures and compares the performance of appending to a Python list versus a collections.deque using timeit.repeat, showing best and average timings.

benchmark performance list
Python
"""Benchmark list.append vs collections.deque.append."""

import timeit

def bench(stmt, setup, repeat=5, number=1_000_000):
    times = timeit.repeat(stmt, setup=setup, repeat=repeat, number=number)
    return min(times), sum(times) / len(times)

if __name__ == "__main__":
    number = 1_000_000
    list_best, list_a…
12 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 medium

How to Benchmark Python Code with pytest-benchmark and mocks

Use pytest-benchmark to measure function performance while combining Mock and patch for controlled test scenarios.

pytest benchmark mock
Python
import time
from unittest.mock import Mock, patch

import pytest
from pytest_benchmark.fixture import BenchmarkFixture


def heavy_operation(data: list[int]) -> int:
    """Simulates a CPU-bound operation."""
    return sum(x * x for x in data)


def test_heavy_operation_benchmark(benchmark: BenchmarkFixture) -> None:…
14 0 Open
Testing & modern typing medium

How to Compare Execution Speed Between Python Functions

Measure and compare the average execution time of multiple Python functions using a reusable benchmark helper with time.perf_counter.

performance benchmarking time
Python
import time
import random

def method_a(values):
    """Sort using built-in sorted."""
    return sorted(values)

def method_b(values):
    """Sort using list's sort method."""
    values_copy = values[:]
    values_copy.sort()
    return values_copy

def method_c(values):
    """Sort manually using bubble sort (slow,…
36 0 Open
Auth & security at scale medium

How to Tune scrypt Parameters in Python

Adjust scrypt work factor (N) to hit a target hashing time with a mock benchmark loop, then return tunable parameters and a derived key.

scrypt hashing password-security
Python
import hashlib

def tune_scrypt_params(target_time=0.1, base_n=2**14, base_r=8, base_p=1):
    """Mock tuning of scrypt params based on target time."""
    n, r, p = base_n, base_r, base_p
    iterations = 0
    
    for _ in range(5):  # simple mock adjustment loop
        iterations += 1
        mock_time = 0.05 + (…
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.