Reference library

Python Code Samples

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

10 matches
Lists & loops easy

Enumerate a Python List with a Custom Start Index

Iterate over a list with an index that starts at a custom value (like 5) using Python's built-in enumerate() function with the start parameter.

enumerate iteration loops
Python
fruits = ["apple", "banana", "cherry", "date"]

for index, fruit in enumerate(fruits, start=5):
    print(f"{index}: {fruit}")
15 0 Open
Lists & loops easy

How to Swap Two Indices in a Python List

Swap two elements at given indices in a Python list using simultaneous assignment, then return the modified list.

list swap indexing
Python
def swap_indices(lst, i, j):
    lst[i], lst[j] = lst[j], lst[i]
    return lst

if __name__ == "__main__":
    my_list = [10, 20, 30, 40, 50]
    print("Original list:", my_list)
    swapped = swap_indices(my_list, 1, 3)
    print("After swapping indices 1 and 3:", swapped)
14 0 Open
Automation & scripting medium

Create a Local Search Engine to Instantly Find Files on Your Computer in Python

Build a local file search engine in Python that indexes files by name, extension, and glob pattern for instant retrieval.

file search indexing os.walk
Python
import os
import sys
import time
from pathlib import Path
import fnmatch

class LocalSearchEngine:
    def __init__(self, root_directory="."):
        self.root_directory = Path(root_directory)
        self.file_index = {}
        
    def build_index(self):
        """Build a complete index of files in the root direc…
43 0 Open
Database scaling & optimization medium

Database Helper in Python with SQLite Scaling Optimization

Build a beginner-friendly SQLite database helper class with WAL, indexed queries, and efficient batch inserts for scaling.

sqlite database scalability
Python
import sqlite3
from contextlib import contextmanager


class DatabaseHelper:
    """Beginner-friendly helper for SQLite database operations with scaling tips."""

    def __init__(self, db_path):
        self.db_path = db_path

    @contextmanager
    def connection(self):
        """Context manager for automatic comm…
14 0 Open
Database scaling & optimization easy

Database indexing and query timing optimization in Python

Create SQLite indexes and time query performance to measure speedup for large table lookups in Python.

sqlite indexing query optimization
Python
import sqlite3
import time


def time_query(db_path, query, params=()):
    conn = sqlite3.connect(db_path)
    conn.execute("PRAGMA journal_mode = WAL")
    start = time.perf_counter()
    result = conn.execute(query, params).fetchall()
    elapsed = time.perf_counter() - start
    conn.close()
    return result, ela…
14 0 Open
Database scaling & optimization medium

How to Create a Covering Index with INCLUDE Columns in Python

Create a covering index with INCLUDE columns in SQLite from Python and inspect the query plan to confirm the index covers the query.

sqlite indexing covering index
Python
import sqlite3

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

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

    employe…
15 0 Open
Database scaling & optimization easy

How to Create a Database Helper Class for Beginners in Python

Build a beginner-friendly SQLite helper class with indexing and batch inserts to optimize database queries in Python.

sqlite database indexing
Python
import sqlite3


class DatabaseHelper:
    def __init__(self, db_path):
        self.connection = sqlite3.connect(db_path)
        self.cursor = self.connection.cursor()

    def create_table_with_index(self, table_name, columns, indexed_column):
        columns_sql = ", ".join(f"{name} {dtype}" for name, dtype in col…
13 0 Open
Database scaling & optimization easy

How to Speed Up Column Lookups with DataFrame Index in Python

Use pandas set_index to make repeated column value lookups O(1)-style fast instead of scanning the whole DataFrame each time.

pandas indexing performance
Python
import pandas as pd

# Mock dataset with duplicate customer IDs
data = {"customer_id": [101, 102, 103, 101, 104, 102],
        "order_amount": [250.0, 85.5, 300.0, 175.25, 420.0, 95.75]}

df = pd.DataFrame(data)
df = df.set_index("customer_id")

# Simulated lookup request
search_id = 102

# Fast index-based lookup (no…
15 0 Open
Database scaling & optimization medium

Simulate a GIN Index for JSONB in Python

Build a mock Generalized Inverted Index (GIN) that flattens JSON documents into key-value tokens for fast lookup queries, mimicking PostgreSQL JSONB indexing.

jsonb gin-index inverted-index
Python
import json
import random
from collections import defaultdict

# Mock GIN (Generalized Inverted Index) for JSONB key-value pairs
class GINIndex:
    def __init__(self):
        self.posting_lists = defaultdict(list)  # token -> list of doc_ids
    
    def index(self, doc_id, json_obj):
        """Index a JSON documen…
14 0 Open
Database scaling & optimization medium

Snowflake ID Generator with Cluster Index Mock in Python

A thread-safe Snowflake ID generator mock that creates unique 64-bit IDs across simulated cluster nodes and maintains a sorted in-memory index for range queries.

snowflake id-generation clustering
Python
import time
import threading

class SnowflakeIDGenerator:
    def __init__(self, machine_id, datacenter_id):
        self.machine_id = machine_id
        self.datacenter_id = datacenter_id
        self.sequence = 0
        self.last_timestamp = -1
        self.machine_bits = 5
        self.datacenter_bits = 5
        …
13 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.