Reference library

Python Code Samples

Easy snippets you can copy, study, and run in the browser editor.

13 matches
Lists & loops easy

How to Reverse a List in Place Without Using reverse() in Python

A two-pointer while loop swaps elements from both ends toward the center to reverse a list in place without creating a copy.

lists in-place two-pointer
Python
def reverse_list_in_place(lst):
    left = 0
    right = len(lst) - 1
    while left < right:
        lst[left], lst[right] = lst[right], lst[left]
        left += 1
        right -= 1


if __name__ == "__main__":
    my_list = [1, 2, 3, 4, 5]
    print("Original:", my_list)
    reverse_list_in_place(my_list)
    prin…
14 0 Open
Lists & loops easy

How to Shuffle a List in Python

Shuffle a Python list in place or return a new shuffled copy using the random module.

random shuffle lists
Python
import random

def shuffle_list(items):
    shuffled = items[:]
    random.shuffle(shuffled)
    return shuffled

if __name__ == "__main__":
    original = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    result = shuffle_list(original)
    print(f"Original: {original}")
    print(f"Shuffled: {result}")
14 0 Open
Files & data easy

How to Copy a File with shutil.copy2 in Python

Copy a file while preserving metadata like timestamps and permissions using Python's shutil.copy2 and pathlib.

shutil file-copy pathlib
Python
import shutil
from pathlib import Path

source = Path("sample.txt")
destination = Path("sample_copy.txt")

source.write_text("Hello, PythonSkillset!")

if __name__ == "__main__":
    shutil.copy2(source, destination)
    copied = destination.read_text()
    print(f"Copied content: {copied}")
    print(f"Source exists:…
11 0 Open
OOP & classes easy

How to Copy Class Instances in Python: Shallow vs Deep Copy

Use copy.copy and copy.deepcopy to clone class instances, showing how nested objects are shared or duplicated.

copy deepcopy shallow copy
Python
import copy


class Config:
    def __init__(self):
        self.settings = {"theme": "dark", "language": "en"}


if __name__ == "__main__":
    original = Config()

    shallow_copy = copy.copy(original)
    deep_copy = copy.deepcopy(original)

    shallow_copy.settings["theme"] = "light"
    deep_copy.settings["them…
13 0 Open
Automation & scripting easy

How to Backup an SQLite Database with a Timestamp in Python

Backs up an SQLite database file to a timestamped copy using the sqlite3 backup API.

sqlite backup automation
Python
import sqlite3
import shutil
from datetime import datetime
from pathlib import Path

def backup_database(db_path: str, backup_dir: str = "backups") -> Path:
    db = Path(db_path)
    backup_folder = Path(backup_dir)
    backup_folder.mkdir(exist_ok=True)
    
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
 …
14 0 Open
Automation & scripting easy

How to Deploy a Static Site Build to an Nginx Directory in Python

Copy a static site build directory into an Nginx web root using Python's shutil and pathlib modules.

automation deployment shutil
Python
import shutil
import os
from pathlib import Path

SRC_DIR = Path("build")
DEST_DIR = Path("/var/www/html")

def deploy_site(src: Path, dest: Path) -> None:
    if not src.exists():
        raise FileNotFoundError(f"Build directory not found: {src}")

    dest.mkdir(parents=True, exist_ok=True)

    for item in src.ite…
16 0 Open
Automation & scripting easy

How to Watch a Folder and Convert New Images in Python

Watch a folder for new files and mock-convert images by copying and renaming them in an output directory.

folder-watching automation pathlib
Python
import time
import hashlib
from pathlib import Path
from datetime import datetime

def mock_convert_image(source: Path, dest_dir: Path) -> Path:
    """Mock image conversion: copy bytes and add .converted suffix."""
    dest = dest_dir / f"{source.stem}.converted{source.suffix}"
    dest.write_bytes(source.read_bytes(…
12 0 Open
Data pipelines & processing easy

Enrich Events with Geo IP Data in Python

Returns a copy of each event dictionary, enriched with a geo-location dict from a mock IP-to-geo lookup table, with a fallback for unknown IPs.

data-enrichment dictionaries pipelines
Python
import ipaddress


GEO_IP_DB = {
    "192.168.1.10": {"country": "US", "city": "New York", "lat": 40.7128, "lon": -74.0060},
    "10.0.0.5": {"country": "DE", "city": "Berlin", "lat": 52.5200, "lon": 13.4050},
    "172.16.0.8": {"country": "JP", "city": "Tokyo", "lat": 35.6762, "lon": 139.6503},
}

EVENTS = [
    {"id…
14 0 Open
Git + Python easy

How to Make a Shallow Clone of an Object in Python

Demonstrates using copy.copy() to create a shallow clone of a Python object, showing how nested mutable data is shared while top-level attributes are independent.

copy shallow-copy clone
Python
import copy


class Config:
    def __init__(self):
        self.settings = {"volume": 50}
        self.user = "admin"


def demonstrate_shallow_copy():
    original = Config()
    shallow = copy.copy(original)

    # Mutating nested object is visible in both (shallow copy share it)
    shallow.settings["volume"] = 90…
14 0 Open
System design patterns easy

How to Implement the Prototype Pattern with Deep Copy in Python

Implements the Prototype design pattern using copy.deepcopy to clone complex objects without sharing mutable state.

prototype-pattern deepcopy dataclasses
Python
import copy
from dataclasses import dataclass, field
from typing import List

@dataclass
class Engine:
    horsepower: int

@dataclass
class Car:
    brand: str
    engine: Engine
    accessories: List[str] = field(default_factory=list)

def clone_prototype(car: Car) -> Car:
    return copy.deepcopy(car)

if __name__ …
13 0 Open
Big data & Spark easy

Hudi Upsert Mock Copy on Write in Python

Simulates Apache Hudi's Copy-on-Write upsert behavior by merging update records into a deep copy of base records, replacing matches or appending new ones.

hudi upsert copy-on-write
Python
import copy
from typing import Dict, List, Any

def upsert_copy_on_write(base_records: List[Dict[str, Any]], updates: List[Dict[str, Any]], key_field: str = "id") -> List[Dict[str, Any]]:
    """Simulate Hudi Copy-on-Write upsert: merge updates into a copy of base records."""
    result = copy.deepcopy(base_records)
 …
14 0 Open
Production deployment patterns easy

How to Mock Multi-Stage Docker Builds in Python

Simulate a multi-stage Docker build in pure Python using classes and temp directories to understand how build stages copy artifacts into a final image.

docker multi-stage simulation
Python
# Simulate multi-stage Docker build with pure Python
from pathlib import Path
import tempfile
import shutil

class BuildContext:
    """Mimics a Docker build context with stages."""
    
    def __init__(self, name):
        self.name = name
        self.files = {}
    
    def add_file(self, dest, content):
        s…
14 0 Open
Production deployment patterns easy

How to Replace Fields in an Immutable Dataclass in Python

Create a new copy of a frozen dataclass with selected fields changed, leaving the original unchanged.

dataclasses immutable configuration
Python
from dataclasses import dataclass, replace


@dataclass(frozen=True)
class ServerConfig:
    name: str
    cpu: int = 2
    ram: int = 4096
    tags: tuple = ()


original = ServerConfig("web-01", cpu=4, tags=("env:prod",))
updated = replace(original, ram=8192, tags=("env:prod", "region:us-east"))

print("Original:", …
15 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.