Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
How to Detect Expired Domains Using Python
Parse a list of domain registration data and compare expiry dates to today to find expired domains.
import datetime
# List of test domains with fake registration and expiry dates
# Format: (domain, registration_date, expiry_date)
test_domains = [
('example.com', '2020-01-15', '2024-01-15'), # Expired
('google.com', '1997-09-15', '2026-09-15'), # Still active
('test-site.org', '2019-06-01', '2023-06-0…
Repeat a string n times with a separator in Python
Repeats a string a given number of times, joining the repetitions with an optional separator, with a guard for non-positive counts.
def repeat_string_with_separator(s, n, sep=''):
"""
Repeats a string n times, joining with a separator.
Args:
s (str): The string to repeat.
n (int): Number of repetitions.
sep (str): Separator between repetitions (default: '').
Returns:
str: The repeated strin…
Find Most Active Contributors in a Repository with Python
Filter recent commits by date and count the most active contributors using Counter and datetime.
from collections import Counter
from datetime import datetime, timedelta
# Simulated commit data
commits = [
{"author": "Alice", "timestamp": datetime.now() - timedelta(days=1)},
{"author": "Bob", "timestamp": datetime.now() - timedelta(days=2)},
{"author": "Alice", "timestamp": datetime.now() - timedelta…
How to Count Occurrences of a Value in a Python List
Counts how many times a specific value appears in a list using a simple loop and a counter variable.
def count_occurrences(data, target):
count = 0
for item in data:
if item == target:
count += 1
return count
if __name__ == "__main__":
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
target_value = 5
result = count_occurrences(numbers, target_value)
print(f"The value {targ…
Benchmark list append vs comprehension in Python
This micro-benchmark compares the speed of building a list with a for loop and append versus a list comprehension, using the timeit module to get precise timings.
import timeit
# Build a list of the first 1,000,000 integers using append in a loop
def append_loop(n=1_000_000):
result = []
for i in range(n):
result.append(i)
return result
# Build the same list using a list comprehension
def comprehension(n=1_000_000):
return [i for i in range(n)]
if __n…
Calculate Time Difference Across Time Zones in Python
Compute the current time difference in hours between two time zones given their UTC offsets using Python's datetime and timezone modules.
from datetime import datetime, timezone, timedelta
def time_difference(from_tz_offset, to_tz_offset):
"""
Calculate time difference in hours between two time zones given their offsets from UTC.
Offsets are in hours (e.g., -5 for EST, +5.5 for IST).
"""
tz1 = timezone(timedelta(hours=from_tz_offset…
Create a retry decorator with max attempts in Python
A decorator that retries a function up to a specified number of times when it raises an exception, with an optional delay between attempts.
import functools
import time
def retry(max_attempts, delay=0.1):
"""Retry a function up to max_attempts times on exception."""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(1, max_attempts + 1):
try:
…
How to Build a Simple Decorator That Logs Function Calls in Python
This code shows how to create a reusable decorator that logs each function call, including arguments, return value, and execution time.
import functools
import time
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__} with args={args}, kwargs={kwargs}")
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} return…
How to Compare Two Implementations with timeit in Python
Measure and compare the execution time of iterative vs recursive factorial functions using the timeit module.
import timeit
def factorial_iterative(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
def factorial_recursive(n):
if n == 0:
return 1
return n * factorial_recursive(n - 1)
if __name__ == "__main__":
n = 10
iterations = 10000
iterative_time = timeit…
How to Create a Timing Decorator in Python
A Python decorator that measures and prints the execution time of any function using time.perf_counter.
import time
from functools import wraps
def timing_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
end = time.perf_counter()
elapsed = end - start
print(f"{func.__name__} took {elapsed:.6f} seconds"…
How to Build a Simple Debug Timer in Python
Create a context manager class to time the execution of a code block with a one-line printout.
import time
class DebugTimer:
"""Context manager that times the execution of a code block."""
def __init__(self, label="Operation"):
self.label = label
self.start_time = None
def __enter__(self):
self.start_time = time.perf_counter()
return self
def __exit__(self, e…
Log to stderr with Python logging basicConfig
Configure Python's logging module to send all log messages to standard error (stderr) instead of the default stderr, with a readable timestamped format.
import logging
def main():
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s — %(name)s — %(levelname)s — %(message)s",
stream=__import__("sys").stderr,
)
logger = logging.getLogger("example")
logger.debug("Debug message")
logger.info("Info message")
logger.…
Retry an Operation on ConnectionError in Python
Retries an unreliable operation a fixed number of times when it raises a transient ConnectionError, with a small delay between attempts.
import time
import random
def unreliable_operation():
"""Simulates an operation that throws ConnectionError occasionally."""
if random.random() < 0.6:
raise ConnectionError("Transient network failure")
return "Operation succeeded"
def retry_operation(attempts=4, delay=0.2):
"""Retries the o…
Generate Timesheet Reports from Daily Logs in Python
Aggregate daily log entries by project and produce a formatted timesheet report using Python's standard library.
import json
from pathlib import Path
from collections import defaultdict
def generate_timesheet_report(daily_logs: list[dict]) -> str:
"""
Generate a timesheet report from daily log entries.
Args:
daily_logs: List of dicts with 'date', 'project', 'hours', 'task' keys
Returns:
…
How to Archive Old Files by Age in Python
Move files older than a specified number of days from a source directory to an archive directory using Python's pathlib and shutil modules.
import os
import shutil
import time
from pathlib import Path
def archive_old_files(source_dir: str, archive_dir: str, days_old: int) -> None:
cutoff_time = time.time() - (days_old * 86400) # 86400 seconds in a day
archive_path = Path(archive_dir)
archive_path.mkdir(parents=True, exist_ok=True)
for i…
How to Build a Dated Backup Filename with Timestamp in Python
Generate unique backup filenames with a timestamp using Python's datetime module and f-strings.
from datetime import datetime
def build_backup_filename(base_name: str, extension: str = "bak") -> str:
"""Generate a dated backup filename with timestamp."""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
return f"{base_name}_{timestamp}.{extension}"
if __name__ == "__main__":
backup_file = bu…
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 List File Metadata in Python
This code walks a directory and returns a list of JSON-ready dicts with each file's name, size, and modification time.
from pathlib import Path
import json
def format_files_data(directory_path):
"""Return a list of JSON-serializable dicts with file metadata."""
base = Path(directory_path)
if not base.is_dir():
raise ValueError(f"Not a directory: {directory_path}")
files_data = []
for file_path in base.ite…
Serialize Python dict to JSON with custom default for datetime
Convert a Python dict containing datetime and set objects into JSON by providing a custom default serializer.
import json
from datetime import datetime
def custom_serializer(obj):
if isinstance(obj, datetime):
return obj.isoformat()
if isinstance(obj, set):
return list(obj)
return str(obj)
data = {
"name": "Alice",
"created_at": datetime(2024, 3, 15, 10, 30, 45),
"tags": {"python", "j…
How to Implement a Singleton Class in Python
This code demonstrates a classic Singleton pattern in Python by overriding __new__ to ensure only one instance of the class is created, even when instantiated multiple times.
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
def __init__(self):
self.value = 0
if __name__ == "__main__":
s1 = Singleton()
s2 = Singleton()
s1.value = 42
print…
Python Factory Method: Create Shapes by Type String
A factory method that maps a type string to a concrete shape class and returns an instance, with runtime error handling.
class Shape:
def draw(self):
raise NotImplementedError
class Circle(Shape):
def draw(self):
return "Drawing a circle"
class Square(Shape):
def draw(self):
return "Drawing a square"
class Triangle(Shape):
def draw(self):
return "Drawing a triangle"
class ShapeFact…
Find Elements Appearing More Than n/3 Times in Python
Return all elements that occur more than len(array)/3 times using a simple dictionary counter.
def majority_third(arr):
"""Return elements appearing more than len(arr)/3 times."""
cutoff = len(arr) / 3
counts = {}
for x in arr:
counts[x] = counts.get(x, 0) + 1
return [x for x, c in counts.items() if c > cutoff]
if __name__ == "__main__":
test1 = [3, 2, 3]
test2 = [1, 1, 1, …
Find First Duplicate Index in Python
Return the index of the first element that appears more than once in a list, using a dictionary for O(n) time.
def find_first_duplicate(arr):
seen = {}
for index, value in enumerate(arr):
if value in seen:
return index
seen[value] = index
return -1
if __name__ == "__main__":
test_array = [3, 5, 2, 8, 5, 1, 2]
result = find_first_duplicate(test_array)
print(f"Array: {test_arr…
How to Count Occurrences of Each Value in Python
Count how many times each value appears in a list using Python's Counter from the collections module.
from collections import Counter
def count_occurrences(values):
"""Return a dictionary mapping each value to its count."""
return dict(Counter(values))
if __name__ == "__main__":
sample_data = ["apple", "banana", "apple", "cherry", "banana", "apple"]
result = count_occurrences(sample_data)
print(r…
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.