Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
Detect Outliers in CSV Data Using Z-Score in Python
Read a CSV file and detect outliers in a numeric column by computing z-scores, flagging those exceeding a given threshold — no machine learning required.
import csv
import statistics
from math import sqrt
def detect_outliers(csv_path, column_name, threshold=2.0):
"""Detect outliers in a numeric column using z-score method."""
values = []
with open(csv_path, 'r', newline='') as f:
reader = csv.DictReader(f)
if column_name not in reader.field…
How to Handle Missing Values in a CSV Numeric Column in Python
Clean missing entries in a CSV numeric column by filling them with the mean, median, a custom value, or dropping rows.
import csv
from pathlib import Path
import statistics
def clean_csv_numeric(input_path: str, output_path: str, column: str, strategy: str = "mean") -> None:
"""
Handles missing values in a numeric column of a CSV file.
Strategies: 'mean', 'median', 'drop', or 'fill' with a specified value.
"""
row…
Convert Lists and Dictionaries to Sets in Python
Convert lists of pairs into dictionaries and lists or dictionaries into sets using simple helper functions.
def convert_to_dict(data):
"""Convert list of tuples or lists into a dictionary."""
return dict(data)
def convert_to_set(data):
"""Convert list or dictionary into a set of its keys/values."""
if isinstance(data, dict):
return set(data.keys())
return set(data)
def convert_collection(data…
How to Use Counter for Most Common Elements in Python
This code demonstrates how to find the most frequent elements in a list using Python's Counter class from the collections module.
from collections import Counter
def most_common_elements(items, n=1):
"""Return the n most common elements and their counts."""
counter = Counter(items)
return counter.most_common(n)
if __name__ == "__main__":
data = ["apple", "banana", "apple", "orange", "banana", "apple", "grape"]
print(most_co…
How to Use Dictionaries and Sets in Python for Beginners
Demonstrates Python dictionary operations and set operations with examples, including access, modification, defaults, and set algebra.
def demonstrate_collections():
# Dictionary basics
student = {
"name": "Alice",
"age": 20,
"courses": ["Math", "Physics"]
}
print("Dictionary:", student)
# Access and modify
student["age"] = 21
student["grade"] = "A"
print("Modified:", student)
# Get with d…
How to Use Dictionaries and Sets in Python for Beginners
Introduces Python dictionaries and sets with practical examples including creating, modifying, and performing set operations, plus a word-frequency counter.
def demonstrate_dict_sets():
# Create a dictionary with basic info
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
print("Dictionary:", person)
# Access and modify dictionary values
person["age"] = 31
person["email"] = "alice@example.com"
print("Afte…
Bucket Numbers into Histogram Bin Counts in Python
Partition a list of numbers into equal-width histogram bins and count how many fall into each bin using only the Python standard library.
from collections import Counter
def histogram_bins(numbers, num_bins):
"""Bucket numbers into histogram bin counts."""
if not numbers:
return []
min_val = min(numbers)
max_val = max(numbers)
bin_width = (max_val - min_val) / num_bins
# Handle edge case where all values are id…
How to Generate Permutations of Length r in Python
Generate and print all r-length permutations of a list using Python's itertools.permutations.
from itertools import permutations
def show_permutations(items, r):
result = list(permutations(items, r))
for perm in result:
print(perm)
print(f"Total: {len(result)}")
if __name__ == "__main__":
data = ["A", "B", "C"]
show_permutations(data, 2)
How to Generate Permutations of Length r in Python
Generate all ordered arrangements of length r from a given list of elements using itertools.permutations.
from itertools import permutations
def generate_permutations(elements, r):
"""Generate all r-length permutations of the given elements."""
return list(permutations(elements, r))
if __name__ == "__main__":
elements = ['A', 'B', 'C']
r = 2
result = generate_permutations(elements, r)
print(f"Ele…
Normalize Data in Python with Comprehensions and Generators
Clean a list by dropping None values with a comprehension, then min-max normalize it using a lazy generator expression — a beginner-friendly data preparation pattern.
import statistics
# Sample raw data including missing and outlier-ish values
raw = [22, 18, None, 25, 30, 19, 22, 17, None, 28, 24]
# Clean the data: drop None values using a list comprehension
clean = [x for x in raw if x is not None]
# Normalize using min-max scaling with a generator expression
min_val = min(clea…
How to Detect Prompt Injection in Python
Implements a regex-based heuristic in Python to flag common prompt injection attempts before sending input to an LLM.
import re
def contains_prompt_injection(user_input: str) -> bool:
# Directives to ignore previous instructions or act as system
ignore_patterns = [
r"\bignore\s+(all\s+)?previous\s+instructions\b",
r"\bdisregard\s+(all\s+)?previous\s+instructions\b",
r"\bdon'?t\s+follow\s+(any\s+)?inst…
Track GitHub Repository Growth in Python
A Python dashboard that fetches and displays GitHub repository statistics including stars, forks, creation date, and recent star activity using the GitHub API.
import requests
import json
from datetime import datetime, timedelta
def track_repo_growth(owner, repo):
url = f"https://api.github.com/repos/{owner}/{repo}"
headers = {"Accept": "application/vnd.github.v3+json"}
response = requests.get(url, headers=headers)
data = response.json()
name = data…
Create ICS Calendar Invites in Python
This script generates a batch of calendar invites in the ICS format using the ics library.
import ics
from datetime import datetime, timedelta
def create_invites(batch):
calendar = ics.Calendar()
for event_data in batch:
event = ics.Event()
event.name = event_data["name"]
event.begin = event_data["start"]
event.end = event_data["end"]
event.description = even…
How to Generate Project Statistics Including Lines of Code and Complexity in Python
Walk through a Python script that scans a project directory for Python files, counts lines of code excluding blanks and comments, and estimates cyclomatic complexity by counting decision keywords.
import os
from pathlib import Path
def count_lines_of_code(filepath):
"""Counts lines of code in a Python file, excluding blank lines and comments."""
try:
with open(filepath, 'r') as f:
lines = f.readlines()
code_lines = [line for line in lines if line.strip() and not line.strip()…
How to Merge PDFs in Python (Mock pypdf Stub)
Merge PDF files by concatenating their raw byte content using a simple stubbed class that mimics the pypdf interface.
import io
from hashlib import sha256
class PdfStub:
def __init__(self, data: bytes, name: str):
self.data = data
self.name = name
def get_content_bytes(self) -> bytes:
return self.data
def merge_pdfs_mock(pdf_stubs) -> bytes:
merged = io.BytesIO()
for stub in pdf_stubs:
…
How to Track GitHub Stars, Forks, and Watchers in Python
Automatically fetch and track stars, forks, and watchers for multiple GitHub repositories, saving snapshots locally as JSON files for historical analysis.
import os
import time
import json
import requests
from pathlib import Path
from datetime import datetime
REPOS = [
"psf/requests",
"python/cpython",
"pallets/flask",
]
DATA_DIR = Path("github_metrics")
def fetch_repo_stats(repo):
url = f"https://api.github.com/repos/{repo}"
resp = requests.get(ur…
Count Records Processed per Category in Python
Use a Counter dictionary to track how many records of each type (ok, error, retry) were processed in a data pipeline.
from collections import Counter
import random
processed_counter = Counter()
def process_records(records):
for record in records:
processed_counter[record] += 1
return len(records)
if __name__ == "__main__":
sample_records = [random.choice(["ok", "error", "retry"]) for _ in range(10)]
print(f…
How to Implement a Sliding Window Average in Python
Compute the average of the most recent N values in a stream using a bounded deque, efficiently updating the total as new values arrive.
from collections import deque
class SlidingWindowAverage:
def __init__(self, window_size):
self.window_size = window_size
self.window = deque(maxlen=window_size)
self.total = 0
def add(self, value):
if len(self.window) == self.window_size:
self.total -= self.windo…
How to detect anomalies in a column using z-score in Python
Detect outliers in a list of numbers using z-score statistics, flagging values that deviate significantly from the mean.
import random
def z_score_anomaly_detection(data, threshold=2.0):
"""
Detect anomalies in a list of numbers using z-score.
"""
mean = sum(data) / len(data)
variance = sum((x - mean) ** 2 for x in data) / len(data)
std_dev = variance ** 0.5
if std_dev == 0:
return []
a…
Create a Mock GitHub Release API in Python for Testing gh CLI
Build an in-memory GitHub Releases API mock that mimics create_release and list_releases for unit testing gh CLI stubs without network calls.
import json
from unittest.mock import patch, Mock
class GitHubReleaseAPI:
"""Mock GitHub Releases API for testing gh CLI stub behavior."""
def __init__(self):
self.releases = {}
self.counter = 1
def create_release(self, repo, tag, name=None, notes=None):
release_id = self…
Create a Cloud Storage Helper Class in Python
Build a simple local file-based helper class that mimics cloud storage operations like save, load, and list JSON objects.
import datetime
import json
from pathlib import Path
class CloudDataHelper:
"""Simple helper for reading/writing JSON files in a cloud-style folder."""
def __init__(self, base_dir: str = "cloud_storage"):
self.base_dir = Path(base_dir)
self.base_dir.mkdir(exist_ok=True)
def save_json(se…
Mock pip-compile to Resolve Requirements in Python
A mock function that mimics pip-compile by converting a requirements.in file into pinned, locked package versions.
import subprocess
import tempfile
from pathlib import Path
def compile_requirements_mock(requirements_in: str) -> str:
"""Mock pip-compile: resolve a simple requirements.in into a locked format."""
lines = [line.strip() for line in requirements_in.splitlines() if line.strip() and not line.startswith("#")]
…
How to Filter Data in Python with Type Hints
A reusable filter_data helper uses optional predicates and numeric bounds with modern Python type hints.
from typing import Iterable, TypeVar, Callable, Any
T = TypeVar("T")
def filter_data(
items: Iterable[T],
predicate: Callable[[T], bool] | None = None,
*,
min_value: float | None = None,
max_value: float | None = None,
) -> list[T]:
"""Filter items by predicate and/or numeric bounds."""
r…
How to Use Python Type Hints for Beginners
Build a data helper module with basic type hints — Union, Optional, List, Dict, Any, and TypeVar — to make your code clearer and safer.
from typing import Any, Union, Optional, List, Dict, Tuple, Callable, TypeVar
T = TypeVar("T")
def describe(value: Any) -> str:
"""Return a human-readable description of the value's type."""
if isinstance(value, list):
return f"list of {len(value)} items"
elif isinstance(value, dict):
ret…
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.