Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Rotate a List in Python
Rotate a list to the right by k positions using Python's list slicing and modulo arithmetic.
def rotate_list_right(lst, k):
if not lst:
return lst
k = k % len(lst)
return lst[-k:] + lst[:-k] if k != 0 else lst
if __name__ == "__main__":
sample = [1, 2, 3, 4, 5, 6, 7]
for k in [0, 1, 3, 8, 20]:
print(f"k={k}: {rotate_list_right(sample, k)}")
Rotate List Left by k Positions in Python
Rotates a list left by k positions using slicing and modulo arithmetic to handle large k safely.
def rotate_left(lst, k):
if not lst:
return []
k = k % len(lst)
return lst[k:] + lst[:k]
if __name__ == "__main__":
my_list = [1, 2, 3, 4, 5]
k = 2
result = rotate_left(my_list, k)
print(f"Original: {my_list}")
print(f"After rotating left by {k}: {result}")
How to Configure Python Logging with File Rotation
A complete demo that sets up a logger with a rotating file handler, writes several log entries, and shows the contents of the current log file.
import logging
from logging.handlers import RotatingFileHandler
logger = logging.getLogger("rotating_logger")
logger.setLevel(logging.DEBUG)
file_handler = RotatingFileHandler(
"app.log",
maxBytes=100,
backupCount=3
)
file_handler.setFormatter(
logging.Formatter("%(asctime)s - %(levelname)s - %(messa…
Rotate Log Files in Python by Size
This code rotates a log file when its size exceeds a threshold, keeping a specified number of backups.
import os
import glob
from pathlib import Path
def rotate_log(log_path, max_size_bytes=1024, max_backups=3):
log_file = Path(log_path)
if log_file.stat().st_size <= max_size_bytes:
print(f"Log size {log_file.stat().st_size} bytes <= threshold, no rotation")
return
for i in range(max_backu…
How to Rotate an Array by k Steps in Python
This code rotates a list to the right by k positions using modulo arithmetic to handle k larger than the list length.
def rotate_array(nums, k):
if not nums:
return []
n = len(nums)
k = k % n
return nums[-k:] + nums[:-k] if k else nums[:]
if __name__ == "__main__":
arr = [1, 2, 3, 4, 5, 6]
k = 2
result = rotate_array(arr, k)
print(f"Original: {arr}")
print(f"Rotated by {k}: {result}")
Python: Archive Old Logs by Compressing Gzip by Age
A Python script that finds .log files older than a specified age and compresses them into .gz archives while removing the originals.
import gzip
import os
import shutil
from pathlib import Path
def archive_logs(log_dir: str, max_age_days: int) -> list[str]:
"""Compress log files older than max_age_days into .gz archives.
Returns a list of compressed file paths.
"""
cutoff = time.time() - max_age_days * 86400
compressed = …
Restrict Secrets File Permissions with the chmod Script in Python
This script restricts a secrets file to 0600 permissions, rotates it to a dated backup, and creates a fresh protected file for secure automation workflows.
import os
import sys
import stat
from pathlib import Path
def restrict_secrets_file(filepath: str) -> None:
"""Set restrictive permissions (0600) on a secrets file."""
path = Path(filepath).expanduser()
if not path.is_file():
raise FileNotFoundError(f"Secrets file not found: {path}")
…
Python Script to Rotate a Leaked API Key
A checklist-driven Python script that scans a codebase for a leaked API key, replaces it with a new one, and prints a step-by-step rotation checklist.
#!/usr/bin/env python3
"""Checklist for rotating a leaked API key across a codebase."""
import re
from pathlib import Path
CHECKLIST = [
"Identify all files containing the leaked key",
"Generate a new key with sufficient entropy",
"Update the secret storage/CI environment variables",
"Replace the ol…
Rotate Log Files by Size in Python
A mock log rotation script that renames log files exceeding a size threshold, appending numbered backups.
import os
from pathlib import Path
def rotate_logs(directory: str, max_size: int = 100) -> None:
"""Rotate log files that exceed max_size bytes."""
log_dir = Path(directory)
for log_file in sorted(log_dir.glob("*.log"), key=lambda p: str(p)):
if log_file.stat().st_size > max_size:
for …
How to Handle mTLS Certificate Rotation in Python
Detect mTLS certificate file changes by tracking modification time and hot-reload the SSL context in a running service.
import ssl
import tempfile
import datetime
from pathlib import Path
class MTLSContext:
def __init__(self, cert_path, key_path, ca_path):
self.cert_path = Path(cert_path)
self.key_path = Path(key_path)
self.ca_path = Path(ca_path)
self.context = None
self.last_loaded_mtime …
How to Implement Refresh Token Rotation in Python
A mock auth service that issues, rotates, and validates refresh tokens, revoking old tokens on reuse to prevent replay attacks.
import time
import hashlib
import secrets
from typing import Dict, Optional, Tuple
class MockTokenService:
"""Simulates refresh token rotation for a simple auth system."""
def __init__(self):
# Token hash -> (user_id, rotation_count, expires_at)
self._active_tokens: Dict[str, Tuple[str, int,…
How to Implement a Vault Dynamic Database Credentials Mock in Python
A Python dataclass-based mock of HashiCorp Vault that issues short-lived database credentials, tracks leases, and revokes them, demonstrating dynamic secrets rotation.
import time
import json
from dataclasses import dataclass, field
from typing import Dict
@dataclass
class DynamicCredential:
username: str
password: str
lease_duration: int
created_at: float = field(default_factory=time.time)
def is_valid(self) -> bool:
return time.time() - self.created_…
How to Mock a TLS Certificate Rotation Schedule in Python
Simulate a TLS certificate rotation schedule with a Python class that tracks last and next rotation dates and decides when to rotate.
import datetime
import random
import time
class CertRotator:
def __init__(self, cert_name, rotation_days=30):
self.cert_name = cert_name
self.rotation_days = rotation_days
self.last_rotated = datetime.date.today() - datetime.timedelta(days=random.randint(10, 25))
self.next_rotatio…
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.