Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
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.
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…
How to Shuffle a List in Python
Shuffle a Python list in place or return a new shuffled copy using the random module.
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}")
Create a Local File Versioning System Using Pure Python
Track file changes locally by copying versions with SHA-256 hashes and JSON metadata using only the Python standard library.
import os
import shutil
import hashlib
import json
import time
from pathlib import Path
class LocalFileVersioning:
def __init__(self, target_dir="versioned_files", versions_dir="versions"):
self.target_dir = Path(target_dir)
self.versions_dir = Path(versions_dir)
self.metadata_file = self.…
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.
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:…
How to Sync Two Folders in Python (Lightweight Backup)
A Python script that synchronizes a source folder to a destination folder, copying new or updated files and removing files that no longer exist in the source.
import os
import shutil
import sys
from pathlib import Path
def sync_folders(src: Path, dst: Path):
"""Sync src folder to dst folder, copying missing/updated files."""
dst.mkdir(parents=True, exist_ok=True)
for src_path in src.rglob("*"):
relative = src_path.relative_to(src)
dst_path = ds…
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.
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…
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.
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")
…
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.
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…
How to Sync Two Directories in Python (rsync-like)
Mirror a source directory into a destination by copying new or changed files and deleting extras, similar to rsync.
import os
import shutil
import sys
from pathlib import Path
def sync_dirs(src: Path, dst: Path):
"""Mirror src into dst: copy new files, overwrite changed, delete extras."""
dst.mkdir(parents=True, exist_ok=True)
for dst_entry in dst.rglob('*'):
rel = dst_entry.relative_to(dst)
src_entry =…
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.
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(…
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.
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…
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.
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…
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.
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…
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.
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__ …
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.
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)
…
How to Expand a Contract and Migrate Data in Python
Expand an old data contract by renaming fields and adding defaults, then migrate to a final version with deepcopy isolation.
import json
from copy import deepcopy
# Mock data representing a user record (old contract)
old_contract = {
"id": 1,
"name": "Alice",
"email": "alice@example.com",
"age": 30,
"status": "active"
}
# Expanded contract: adds fields with defaults and renames some fields
expand_rules = {
"id": "u…
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.
# 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…
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.
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:", …
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
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- 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.