Reference library

Python Code Samples

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

29 matches
Strings & text easy

How to Count Words in a String in Python

Split a paragraph on whitespace and return the number of words using Python's built-in string methods.

strings word-count split
Python
def count_words(paragraph: str) -> int:
    words = paragraph.split()
    return len(words)


if __name__ == "__main__":
    paragraph = "The quick brown fox jumps over the lazy dog."
    result = count_words(paragraph)
    print(f"Word count: {result}")
13 0 Open
Files & data medium

Build a Secure Local Password Vault with Encrypted Storage in Python

A Python class that stores and retrieves passwords in an encrypted JSON file using Fernet symmetric encryption from the cryptography library.

encryption security passwords
Python
import json
import os
import base64
import hashlib
from cryptography.fernet import Fernet
from getpass import getpass

class PasswordVault:
    def __init__(self, vault_file="vault.json", key_file="vault.key"):
        self.vault_file = vault_file
        self.key_file = key_file
        self.key = self._load_or_creat…
46 0 Open
Files & data medium

Encrypt and Decrypt Files Using Python

Encrypt and decrypt files using the cryptography library's Fernet symmetric encryption.

encryption decryption fernet
Python
import os
from pathlib import Path
from cryptography.fernet import Fernet

def generate_key(key_file: Path) -> bytes:
    key = Fernet.generate_key()
    key_file.write_bytes(key)
    return key

def load_key(key_file: Path) -> bytes:
    return key_file.read_bytes()

def encrypt_file(input_path: Path, key: bytes, out…
56 0 Open
Dictionaries & sets easy

Build adjacency dict graph from edges in Python

Convert a list of edges into an undirected adjacency dictionary, mapping each node to its neighbors, with sorted output.

graph adjacency dictionary
Python
def build_adjacency_dict(edges):
    graph = {}
    for u, v in edges:
        if u not in graph:
            graph[u] = []
        if v not in graph:
            graph[v] = []
        graph[u].append(v)
        graph[v].append(u)
    return graph

if __name__ == "__main__":
    edges = [(1, 2), (2, 3), (3, 4), (4, 1)…
12 0 Open
Dictionaries & sets medium

How to Implement Disjoint Set Union Find in Python

Implement a Disjoint Set Union-Find data structure using a Python dictionary for parent tracking, with path compression and connectivity checks.

disjoint-set union-find graph
Python
class DisjointSet:
    def __init__(self):
        self.parent = {}

    def find(self, x):
        # Path compression
        if self.parent[x] != x:
            self.parent[x] = self.find(self.parent[x])
        return self.parent[x]

    def union(self, x, y):
        # Initialize if not present
        if x not in…
13 0 Open
OOP & classes easy

Graph Class with Adjacency Dict in Python

Build an undirected graph class using a dictionary of adjacency lists with methods to add vertices, edges, remove edges, and query neighbors.

graph oop adjacency-list
Python
class Graph:
    def __init__(self):
        self.adjacency = {}

    def add_vertex(self, vertex):
        if vertex not in self.adjacency:
            self.adjacency[vertex] = []

    def add_edge(self, u, v):
        self.add_vertex(u)
        self.add_vertex(v)
        self.adjacency[u].append(v)
        self.adja…
11 0 Open
Algorithms & data structures easy

Depth First Search Traversal Order in Python

Recursive depth-first search that returns the visit order of nodes in an adjacency list graph starting from a given node.

dfs graph traversal
Python
def dfs_order(adj, start):
    visited = set()
    order = []

    def dfs(node):
        visited.add(node)
        order.append(node)
        for neighbor in adj.get(node, []):
            if neighbor not in visited:
                dfs(neighbor)

    dfs(start)
    return order


if __name__ == "__main__":
    # Dem…
15 0 Open
Algorithms & data structures easy

How to Get the Breadth-First Traversal Order of a Graph in Python

Performs a breadth-first search on an adjacency list and returns the order nodes are visited, using a deque for efficient queue operations.

graph bfs queue
Python
from collections import deque

def bfs_order(adjacency, start=0):
    """Return the order nodes are visited in a breadth-first traversal."""
    visited = set()
    order = []
    queue = deque([start])
    visited.add(start)

    while queue:
        node = queue.popleft()
        order.append(node)

        for neig…
13 0 Open
Automation & scripting easy

Build a Command-Line Password Generator in Python

Generate cryptographically strong random passwords using Python's secrets module and print them for command-line use.

secrets password-generator automation
Python
import secrets
import string

def generate_password(length=16):
    """Generate a cryptographically strong random password."""
    alphabet = string.ascii_letters + string.digits + string.punctuation
    password = ''.join(secrets.choice(alphabet) for _ in range(length))
    return password

if __name__ == "__main__":…
47 0 Open
Automation & scripting medium

Detect Circular Imports Across Python Projects Automatically

This script walks through all .py files in a directory, builds an import graph, and uses depth-first search to find cycles—printing each circular dependency chain.

circular-imports import-graph ast
Python
import ast
import sys
from pathlib import Path
from collections import defaultdict, deque

def find_imports(filepath):
    """Return set of module names imported by a Python file."""
    imports = set()
    try:
        with open(filepath) as f:
            tree = ast.parse(f.read())
    except (SyntaxError, UnicodeDe…
36 0 Open
Automation & scripting medium

Extract Every Open Graph and Social Media Meta Tag from Web Pages in Python

A Python script that fetches a webpage and extracts all Open Graph, Twitter Card, Facebook, and Article meta tags using the standard library HTML parser.

meta tags open graph twitter cards
Python
from html.parser import HTMLParser
import re
from urllib.request import urlopen
from urllib.parse import urlparse

class MetaExtractor(HTMLParser):
    def __init__(self):
        super().__init__()
        self.meta_tags = []
    
    def handle_starttag(self, tag, attrs):
        if tag == 'meta':
            attrs_…
32 0 Open
Automation & scripting medium

Generate Strong SSH Keys and Save Them Securely with Python

Generate a 4096-bit RSA SSH key pair using Python's cryptography library and save both private and public keys with restricted file permissions.

ssh key-generation cryptography
Python
import os
import stat
from pathlib import Path
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend

def generate_ssh_keypair(key_path: str = "id_rsa", passphrase: str = None):
    """Generate a 4096-…
34 0 Open
Automation & scripting medium

How to Create a Link Graph Visualization for Any Website in Python

A Python script that crawls a website's internal links, builds a directed graph of parent-child URL relationships, and prints the graph to the console.

crawler graph visualization
Python
import requests
from bs4 import BeautifulSoup
from collections import defaultdict
from urllib.parse import urljoin, urlparse
import sys

def get_links(url, max_links=20):
    try:
        response = requests.get(url, timeout=5)
        soup = BeautifulSoup(response.text, 'html.parser')
        base_url = f"{urlparse(u…
38 0 Open
Automation & scripting medium

How to Generate a Dependency Graph for Python Projects

This script walks through a Python project directory, parses each .py file's imports, and prints a dependency graph showing which modules depend on which other modules.

ast dependency graph import parsing
Python
import os
import ast
from pathlib import Path
from collections import defaultdict

def get_imports(filepath):
    with open(filepath) as f:
        try:
            tree = ast.parse(f.read())
        except SyntaxError:
            return []
    imports = []
    for node in ast.walk(tree):
        if isinstance(node, …
37 0 Open
Data pipelines & processing medium

How to Topologically Sort a DAG in Python

Compute a valid execution order for tasks with dependencies using Kahn's algorithm in Python.

dag topological-sort graph
Python
from collections import defaultdict, deque


def topological_order(dependencies):
    graph = defaultdict(list)
    in_degree = defaultdict(int)
    tasks = set(dependencies.keys())

    for task, depends_on in dependencies.items():
        for d in depends_on:
            graph[d].append(task)
            in_degree[t…
10 0 Open
Git + Python easy

Build a Simple Log Graph in Python

Create a basic one-dimensional bar chart from log lines by counting occurrences of leading numeric keys.

logging visualization graph
Python
import heapq


def log_graph(log_lines: list[str]) -> str:
    """Build a simple per-line, one-dimensional visual graph from log entries."""
    counts: dict[int, int] = {}
    for line in log_lines:
        tokens = line.split()
        if tokens:
            try:
                idx = int(tokens[0])
            exce…
16 0 Open
API design & gRPC easy

How to Mock a GraphQL Query Type in Python

Create a lightweight mock of a GraphQL Query type to simulate repository lookups without a server.

graphql mock resolver
Python
import json

class Query:
    def __init__(self):
        self.starred_repos = [
            {"id": 1, "name": "graphql", "owner": "graphql"}
        ]

    def repository(self, name):
        if name == "graphql":
            return {"id": 1, "name": "graphql", "stargazerCount": 85000}
        return None


if __name…
13 0 Open
Microservices patterns medium

How to Mock a Choreography Saga in Python

Simulate a choreography-based saga with event envelopes, status tracking, and compensating actions to model distributed transactions.

saga microservices events
Python
import json
from dataclasses import dataclass, asdict
from typing import List, Optional
from enum import Enum


class SagaStatus(Enum):
    PENDING = "PENDING"
    COMPLETING = "COMPLETING"
    COMPLETED = "COMPLETED"
    FAILED = "FAILED"


@dataclass
class EventEnvelope:
    event_type: str
    order_id: str
    sta…
12 0 Open
Microservices patterns easy

How to Mock a GraphQL Backend in Python

Create an in-memory GraphQL mock backend using dataclasses and resolver methods returning plain dictionaries.

graphql mock dataclasses
Python
from dataclasses import dataclass, asdict
from typing import Any, Dict, List


@dataclass
class Product:
    id: int
    name: str
    price: float


@dataclass
class User:
    id: int
    username: str


class MockGraphQLBackend:
    def __init__(self) -> None:
        self.products = [
            Product(id=1, name…
14 0 Open
Big data & Spark medium

How to Build a DAG Execution Stage Calculator in Python

Computes the execution stages of a directed acyclic graph (DAG) by grouping nodes that become ready simultaneously using topological sorting with Kahn's algorithm.

dag topological-sort kahn-algorithm
Python
from collections import defaultdict, deque


def get_stages(edges):
    """Return list of stages, where each stage is a list of nodes
    that become ready at the same time in a DAG."""
    graph = defaultdict(list)
    in_degree = defaultdict(int)
    nodes = set()

    for src, dst in edges:
        graph[src].appen…
14 0 Open
Database scaling & optimization easy

Geo shard by region in Python

Maps users to database shards based on geographic region with a deterministic hash fallback.

sharding geolocation database
Python
import json
from collections import defaultdict

REGION_SHARD_MAP = {
    "na": ["shard-01", "shard-02"],
    "eu": ["shard-03", "shard-04", "shard-05"],
    "ap": ["shard-06"],
    "sa": ["shard-07", "shard-08"],
}

# user_id -> region (mock lookup)
USER_REGIONS = {
    "u_1001": "na",
    "u_1002": "eu",
    "u_1003…
12 0 Open
Auth & security at scale medium

AES GCM encryption and decryption in Python

Encrypt and decrypt data with AES-256-GCM using the cryptography library, including nonce generation and authenticated roundtrip verification.

aes-gcm cryptography encryption
Python
import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

def aes_gcm_demo():
    plaintext = b"confidential message"
    key = AESGCM.generate_key(bit_length=256)
    aesgcm = AESGCM(key)
    nonce = os.urandom(12)
    
    ciphertext = aesgcm.encrypt(nonce, plaintext, None)
    decrypted = aesgcm.dec…
18 0 Open
Auth & security at scale medium

ECDH key agreement in Python with cryptography

Simulate ECDH key exchange between Alice and Bob, derive a shared secret, and generate a symmetric key with HKDF using the cryptography library.

ecdh cryptography key-agreement
Python
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.kdf.hkdf import HKDF

def ecdh_mock():
    # Alice generates her key pair
    alice_private = ec.generate_private_key(ec.SECP256R1())
    alice_public = alice_pr…
15 0 Open
Auth & security at scale easy

How to Generate PKCE Code Challenge in Python

This Python script generates a PKCE code verifier and its corresponding S256 code challenge for secure OAuth2 authorization flows.

pkce oauth2 security
Python
import base64
import hashlib
import os
import secrets
import string

def generate_code_verifier(length=64):
    alphabet = string.ascii_letters + string.digits + "-._~"
    return "".join(secrets.choice(alphabet) for _ in range(length))

def generate_code_challenge(code_verifier, method="S256"):
    if method == "S256…
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.