Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Validate List Data in Python
A beginner-friendly validation helper that checks if data is a list, enforces minimum length, and optionally verifies item types with clear error messages.
def validate_data(data, expected_types=None, min_length=1):
"""Validate that data is a non-empty list and optionally check item types."""
if not isinstance(data, list):
return False, f"Expected a list, got {type(data).__name__}"
if len(data) < min_length:
return False, f"List must have…
Round Robin Merge Multiple Lists in Python
Merge multiple lists by taking one element from each in turn, stopping when all lists are exhausted.
from itertools import cycle
def round_robin_merge(*lists):
"""Merge multiple lists by taking one element from each in turn."""
result = []
max_len = max(len(lst) for lst in lists)
for i in range(max_len):
for lst in lists:
if i < len(lst):
result.append(lst[i])…
Build a Progress Callback Function for Loops in Python
Create a reusable progress callback that receives per-step data and lets callers log or update a UI as a loop runs.
def run_with_progress(items, desc="Processing", step_callback=None):
"""Run a loop with progress updates via callback."""
total = len(items)
for idx, item in enumerate(items):
# Process the item (simulated work here)
result = item * 2
# Build progress data dictionary
if ste…
Cache expensive function with lru_cache in Python
Use functools.lru_cache to memoize an expensive recursive function and show the dramatic speedup on repeated calls.
from functools import lru_cache
import time
@lru_cache(maxsize=128)
def expensive_operation(n):
"""Simulate an expensive Fibonacci-like calculation."""
if n < 2:
return n
return expensive_operation(n - 1) + expensive_operation(n - 2)
if __name__ == "__main__":
# First call (uncached) - take…
Call a Function Dynamically by Name in Python
Use globals() to look up and call a function by its name as a string, with optional arguments.
def greet():
return "Hello from greet!"
def add(a, b):
return a + b
def multiply(a, b):
return a * b
if __name__ == "__main__":
func_name = "add"
args = (3, 5)
# Call function dynamically by name from globals
result = globals()[func_name](*args)
print(f"{func_name}({', '.join(ma…
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 Compose Two Functions into a Single Callable in Python
Combine two Python functions into a single callable using a compose helper, then apply the chained call.
def add_one(x):
return x + 1
def double(x):
return x * 2
def compose(f, g):
return lambda x: f(g(x))
add_then_double = compose(double, add_one)
double_then_add = compose(add_one, double)
result1 = add_then_double(5)
result2 = double_then_add(5)
print(f"add_one then double(5) = {result1}")
print(f"doub…
How to Convert a List to an Iterator in Python with iter()
This code converts a list into an iterator using the built-in iter() function and retrieves items sequentially with next(), handling exhaustion with StopIteration.
def main():
# Original list
fruits = ["apple", "banana", "cherry"]
# Convert the list to an iterator using iter()
fruit_iterator = iter(fruits)
# Retrieve items one at a time with next()
print(next(fruit_iterator)) # apple
print(next(fruit_iterator)) # banana
print(next(fruit_iterat…
How to Count Items with Default Parameters in Python
Define a Python function that prints each item with a running counter, using default parameters to allow custom start values and step increments.
def count_items(items, start=0, step=1):
"""Count items in a list with configurable start value and step."""
count = start
for item in items:
print(f"{count}: {item}")
count += step
if __name__ == "__main__":
fruits = ["apple", "banana", "cherry"]
print("Default parameters (start=0…
How to Create a Counter Closure in Python
Build a closure in Python that remembers and increments a counter across calls without using global variables.
def create_counter(start=0):
count = start
def increment():
nonlocal count
count += 1
return count
return increment
if __name__ == "__main__":
counter = create_counter(10)
print(counter())
print(counter())
print(counter())
How to Define a Function with Default Parameter Values in Python
This code demonstrates defining a Python function with default parameter values, showing how to call it with zero, one, or two arguments.
def greet(name: str = "World", punctuation: str = "!") -> str:
"""Return a greeting message using default parameter values."""
message = f"Hello, {name}{punctuation}"
return message
if __name__ == "__main__":
# Call with no arguments – uses both defaults
print(greet())
# Call with one argume…
How to Group a List into Chunks in Python
Split a list into smaller groups of a fixed size using a reusable function with a default parameter.
def make_groups(numbers, group_size=2):
"""Splits a list into smaller groups of a given size."""
groups = []
for i in range(0, len(numbers), group_size):
groups.append(numbers[i:i + group_size])
return groups
if __name__ == "__main__":
data = [1, 2, 3, 4, 5, 6, 7]
print("Default size…
How to Implement Memoized Fibonacci in Python with functools.cache
Use functools.cache to memoize a recursive Fibonacci function, avoiding repeated computation and dramatically speeding up the calculation.
from functools import cache
@cache
def fibonacci(n: int) -> int:
"""Return the n-th Fibonacci number (0-indexed)."""
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
if __name__ == "__main__":
for i in range(10):
print(f"fibonacci({i}) = {fibonacci(i)}")
print(f"Cache…
How to Implement a Trampoline for Tail Recursion in Python
This code implements a trampoline decorator that converts tail-recursive functions into iterative loops, allowing deep recursion without hitting Python's recursion limit.
def trampoline(fn):
"""Convert a tail-recursive function into an iterative loop."""
def wrapper(*args, **kwargs):
result = fn(*args, **kwargs)
while callable(result):
result = result()
return result
return wrapper
@trampoline
def factorial(n, acc=1):
"""Tail-recursi…
How to Invalidate Cache When Arguments Change in Python
A memoization decorator that caches function results keyed by arguments, automatically invalidating when inputs change.
from functools import wraps
def memoize(func):
cache = {}
@wraps(func)
def wrapper(*args, **kwargs):
key = (args, tuple(sorted(kwargs.items())))
if key not in cache:
cache[key] = func(*args, **kwargs)
return cache[key]
return wrapper
@memoize
def expensiv…
How to Load a .env File Manually in Python
Parse a .env-style key-value file into a Python dictionary using only the standard library, with comment and quoted-value handling.
import re
from pathlib import Path
def load_dotenv_file(filepath: str) -> dict[str, str]:
"""Parse a .env-style file into a dictionary."""
env = {}
path = Path(filepath)
if not path.exists():
raise FileNotFoundError(f"Environment file not found: {filepath}")
for line in path.read_text()…
How to Merge Lists in Python with Default Parameters
This Python function merges two lists using the + operator and demonstrates default parameters, allowing the second argument to be omitted.
def merge_lists(list1, list2=["default"]):
"""Merge two lists and return the combined result."""
return list1 + list2
if __name__ == "__main__":
# Example with default parameter
print("With default:", merge_lists([1, 2, 3]))
# Example with both arguments provided
print("With custom:", me…
How to Parse Command Line Arguments in Python with argparse
Build a CLI that accepts positional integers, an optional --sum flag, and a --verbose switch, all with Python's standard argparse library.
import argparse
def main():
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('numbers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
…
How to Parse Function Parameters with Defaults in Python
Create Python functions with default parameter values to make arguments optional and provide sensible fallbacks.
def greet(name, greeting="Hello", punctuation="!"):
"""Greet a person with customizable greeting and punctuation."""
return f"{greeting}, {name}{punctuation}"
def describe_fruit(fruit, color="unknown", ripe=False):
"""Describe a fruit with optional attributes."""
status = "ripe" if ripe else "not ripe…
How to Pass a Function as a Callback to map and filter in Python
Shows how to apply custom functions to every element of a list using map and filter callbacks in Python.
def double(x):
return x * 2
def is_even(x):
return x % 2 == 0
if __name__ == "__main__":
numbers = [1, 2, 3, 4, 5]
doubled = list(map(double, numbers))
evens = list(filter(is_even, numbers))
print("Original:", numbers)
print("Doubled:", doubled)
print("Evens:", evens)
How to Print Colored Text in Python with ANSI Codes
Define a small Colors class and a colored() helper to print styled terminal text using ANSI escape codes.
class Colors:
RESET = "\033[0m"
RED = "\033[31m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
BLUE = "\033[34m"
MAGENTA = "\033[35m"
CYAN = "\033[36m"
WHITE = "\033[37m"
BOLD = "\033[1m"
UNDERLINE = "\033[4m"
def colored(text, color):
return f"{color}{text}{Colors.RESET}"
if _…
How to Read Environment Variables in Python with Default Values
Retrieve an environment variable safely using os.getenv() with a fallback default when the variable is missing.
import os
database_url = os.getenv("DATABASE_URL", "postgresql://localhost:5432/mydb")
print(f"Database URL: {database_url}")
How to Use Default Parameter Values in Python Functions
Shows how to define and call Python functions with default parameter values, including overriding some or all defaults and using keyword arguments.
def greet(name, greeting="Hello", punctuation="!"):
"""Return a greeting message using default parameters."""
return f"{greeting}, {name}{punctuation}"
if __name__ == "__main__":
# Using defaults
print(greet("Alice"))
# Overriding first default
print(greet("Bob", "Hi"))
# Overrid…
How to Use Default Parameter Values in Python Functions
This code demonstrates how to define a Python function with default parameters and call it with varying numbers of arguments to see the defaults applied.
def greet(name, greeting="Hello", punctuation="!"):
message = f"{greeting}, {name}{punctuation}"
print(message)
if __name__ == "__main__":
greet("Alice")
greet("Bob", "Hi")
greet("Charlie", "Hey", "?")
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.