Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
How to Compare Strings with casefold in Python
Compares two strings ignoring case differences using the casefold() method for proper Unicode normalization.
def compare_strings(str1: str, str2: str) -> bool:
return str1.casefold() == str2.casefold()
if __name__ == "__main__":
tests = [
("HELLO", "hello"),
("Straße", "STRASSE"),
("Python", "Python"),
("Mixed Case", "mixed case"),
]
for s1, s2 in tests:
print(f"{s1!r}…
How to Compare Two Strings in Python
Compares two string values and returns a detailed report with equality, case-insensitive comparison, lengths, and uppercase versions.
def compare_data(first_value, second_value):
"""Compare two string values and return a report."""
if first_value == second_value:
status = "MATCH"
else:
status = "DIFFER"
return {
"first_value": first_value,
"second_value": second_value,
"status": status,
…
Compare Two Lists in Python: Common, Only in First, Only in Second
A beginner-friendly helper that loops over two lists and returns items common to both, items only in the first list, and items only in the second list.
def compare_lists(list1, list2):
common = []
only_in_first = []
only_in_second = []
for item in list1:
if item in list2:
common.append(item)
else:
only_in_first.append(item)
for item in list2:
if item not in list1:
only_in_second…
Find Maximum Value in a List of Numbers in Python
Iterate through a list with a for loop to manually find and return the maximum numeric value.
def find_max(numbers):
"""Return the maximum value in a list of numbers."""
if not numbers:
return None
max_value = numbers[0]
for num in numbers[1:]:
if num > max_value:
max_value = num
return max_value
if __name__ == "__main__":
sample_list = [3, 7, 2, 15, 9, 11]
…
Find Minimum Value in a List in Python
This code defines a function that finds and returns the minimum value in a list of numbers, handling empty lists gracefully by returning None.
def find_minimum(numbers):
"""
Find and return the minimum value in a list of numbers.
Args:
numbers: List of numeric values
Returns:
The minimum value, or None if the list is empty
"""
if not numbers:
return None
min_value = numbers[0]
for num in n…
How to Use Default Parameters in Python Functions
A beginner-friendly Python function that uses default parameters to compare two numbers with equal, greater, or less operations.
def compare(a, b, operation="equal"):
if operation == "equal":
return a == b
elif operation == "greater":
return a > b
elif operation == "less":
return a < b
else:
return f"Unknown operation: {operation}"
if __name__ == "__main__":
print(compare(5, 5))
print(com…
Compare Two Folder Structures and Find Differences in Python
Walks two directories using os.walk, builds sets of relative paths, and prints items that exist in only one folder.
import os
def compare_folders(path1, path2):
"""
Compare the file/folder structure of two directories and print differences.
"""
def get_structure(root):
structure = set()
for dirpath, dirnames, filenames in os.walk(root):
rel_path = os.path.relpath(dirpath, root)
…
How to Compare Directory Trees in Python
This code recursively scans two directory trees and reports files that exist in only one directory, as well as files present in both but with different content.
from pathlib import Path
def compare_directories(path1, path2):
dir1 = Path(path1)
dir2 = Path(path2)
if not dir1.is_dir() or not dir2.is_dir():
raise ValueError("Both paths must be directories.")
files1 = {p.relative_to(dir1) for p in dir1.rglob("*") if p.is_file()}
files2 = {p.relative…
Compare Two Dictionaries in Python
Compare two dictionaries by finding common keys, unique keys, and value differences using Python's set operations.
def compare_data(dict1, dict2):
"""Compare two dictionaries and summarize similarities/differences."""
keys1 = set(dict1.keys())
keys2 = set(dict2.keys())
common_keys = keys1 & keys2
only_in_first = keys1 - keys2
only_in_second = keys2 - keys1
print(f"Common keys ({len(common_keys…
How to Diff Two Dicts in Python: Added, Removed, and Changed Keys
Compare two dictionaries and report added, removed, and changed keys using Python's set operations on dict keys.
def diff_dicts(old: dict, new: dict) -> dict:
"""Compare two dicts and report added, removed, and changed keys."""
added = {k: new[k] for k in new.keys() - old.keys()}
removed = {k: old[k] for k in old.keys() - new.keys()}
common_keys = old.keys() & new.keys()
changed = {k: (old[k], new[k]) for k …
How to Find Keys with Matching Values in Two Dictionaries in Python
Find dictionary keys where both dictionaries have the exact same value by iterating over key-value pairs and comparing them.
def find_matching_values(dict1, dict2):
"""Return list of keys that have the same value in both dicts."""
matches = []
for key, value in dict1.items():
if key in dict2 and dict2[key] == value:
matches.append(key)
return matches
if __name__ == "__main__":
# Example usage
di…
How to Find Symmetric Difference Between Two Python Sets
Compute elements unique to each set and build a flag dictionary showing membership across two Python sets.
def symmetric_difference_with_flags(set_a, set_b):
"""Return elements in either set but not both, grouped by which set they came from."""
only_in_a = set_a - set_b
only_in_b = set_b - set_a
print(f"Only in A: {only_in_a}")
print(f"Only in B: {only_in_b}")
print(f"Symmetric difference: {onl…
How to Sort Dictionary Keys Alphabetically in Python
This code returns a list of dictionary keys sorted alphabetically, using a case-insensitive comparison while preserving the original insertion order for keys that are equal.
data = {
"banana": 3,
"apple": 1,
"Cherry": 5,
"date": 2,
"apple": 4,
"Fig": 6,
"banana": 2,
}
def sort_dict_keys_alphabetically(d):
"""Return a list of keys sorted alphabetically (case-insensitive), stable for duplicates."""
return sorted(d.keys(), key=lambda k: k.lower())
if __n…
How to Compare Dataclass Instances by Specific Fields in Python
Use @dataclass(order=True) with field(compare=False) to control which fields determine ordering and equality between instances.
from dataclasses import dataclass, field
from typing import Any
@dataclass(order=True)
class Person:
name: str = field(compare=False)
age: int
height_cm: float
priority: int = field(compare=False, default=0)
def __repr__(self):
return f"Person(name={self.name!r}, age={self.age}, height={s…
How to Implement Rich Comparison Ordering in Python Classes
This code demonstrates how to implement rich comparison operators (like <, <=, >, >=, ==, !=) in a Python class by defining __lt__ and __eq__, enabling sorting and ordering of custom objects.
class Task:
def __init__(self, priority, name):
self.priority = priority
self.name = name
def __lt__(self, other):
if not isinstance(other, Task):
return NotImplemented
return self.priority < other.priority
def __eq__(self, other):
if not isinstance(oth…
How to Use IntEnum Arithmetic for Priority Levels in Python
Demonstrates Python IntEnum arithmetic for priority levels, showing how enum members behave like integers in calculations and comparisons.
from enum import IntEnum
class Priority(IntEnum):
LOW = 1
MEDIUM = 5
HIGH = 10
CRITICAL = 20
if __name__ == "__main__":
current = Priority.MEDIUM
boosted = current + 3
lowered = current - 2
doubled = current * 2
print(f"Current: {current} ({current.value})")
print(f"Boosted (…
Python object equality: id vs value comparison
Demonstrates the difference between default identity comparison and custom equality, with a value-based class implementing __eq__ and __hash__.
import copy
class IdOnly:
def __init__(self, name):
self.name = name
class ValueId:
def __init__(self, name):
self.name = name
def __eq__(self, other):
return isinstance(other, ValueId) and self.name == other.name
def __hash__(self):
return hash(self.name)
def…
How to Compare Two Lists Elementwise for Greater Flags in Python
Compare two equal-length lists element by element and return a list of booleans marking where list_a values are greater than list_b values.
def compare_lists_greater(list_a, list_b):
"""
Compare two lists elementwise and return a list of booleans
indicating whether each element in list_a is greater than the
corresponding element in list_b.
"""
if len(list_a) != len(list_b):
raise ValueError("Lists must have the same length"…
How to Compare Files and Show a Diff in Python
Compare two text files and print a unified diff using Python's difflib module to highlight differences.
import difflib
from pathlib import Path
def compare_files(expected_path: str, actual_path: str) -> str:
"""Compare two text files and return a unified diff."""
expected = Path(expected_path).read_text()
actual = Path(actual_path).read_text()
diff = difflib.unified_diff(
expected.splitlines(ke…
Compare Model A vs Model B Metrics in Python
A script that simulates and compares metrics between two ML models, showing a formatted diff table for quick insight.
import random
def compare_a_b(samples=5):
"""Mock comparison of model A vs model B predictions."""
metrics = ["accuracy", "precision", "recall", "f1"]
print(f"{'Metric':<12}{'Model A':>10}{'Model B':>10}{'Diff':>10}")
print("-" * 42)
random.seed(42)
for metric in metrics:
a = round(r…
Bonferroni Correction in Python
Applies the Bonferroni correction to a list of p-values to control the family-wise error rate when performing multiple comparisons.
import numpy as np
def bonferroni_correction(p_values, alpha=0.05):
"""Apply Bonferroni correction to a list of p-values."""
n = len(p_values)
corrected_alpha = alpha / n
significant = [p < corrected_alpha for p in p_values]
return corrected_alpha, significant
if __name__ == "__main__":
# Moc…
How to Count Star vs Estimate Matches in Python
Count how many times 'star' and 'estimate' annotations match their actual labels in a list of mock comparison results.
def count_star_vs_estimate(mock_scores):
"""
Count the number of times 'star' wins and 'estimate' wins
from a list of mock comparison results.
Args:
mock_scores: list of tuples, each (annotation, actual)
where annotation is 'star' or 'estimate'
Returns:
dict w…
How to Hash and Verify Passwords in Python
Hash passwords securely with PBKDF2-SHA256 and verify them using a constant-time comparison.
import hashlib
import hmac
import secrets
from typing import Tuple
def hash_password(password: str, salt: str = None) -> Tuple[str, str]:
"""Hash a password with a random salt using PBKDF2-SHA256."""
salt = salt or secrets.token_hex(16)
hashed = hashlib.pbkdf2_hmac(
"sha256", password.encode("utf…
How to Salt Passwords per User in Python
Hash each user's password with a unique random salt using hashlib, and verify logins with timing-safe comparison.
import hashlib
import secrets
def hash_password(password: str, salt: str | None = None) -> tuple[str, str]:
"""Hash a password with a random salt (or provided salt).
Returns:
(salt_hex, password_hash_hex)
"""
if salt is None:
salt = secrets.token_hex(16)
salted = (salt + password)…
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.