Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
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 Create a Higher-Order Function in Python (Apply Twice)
This code defines a higher-order function that takes another function and a value, then applies the function twice to the value and returns the result.
def apply_twice(func, value):
return func(func(value))
def add_ten(x):
return x + 10
def square(x):
return x ** 2
if __name__ == "__main__":
print(apply_twice(add_ten, 5))
print(apply_twice(square, 3))
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 Document Python Functions with Google Style Docstrings
Document a Python function with a Google style docstring to describe arguments and return values clearly.
def calculate_rectangle_area(length: float, width: float) -> float:
"""Calculate the area of a rectangle.
Args:
length (float): The length of the rectangle in meters.
width (float): The width of the rectangle in meters.
Returns:
float: The area of the rectangle in square meters.
…
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 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 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 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 Pipe Data Through a List of Transform Functions in Python
Applies a sequence of functions to an initial value using functools.reduce, creating a reusable pipe utility.
from functools import reduce
def pipe(data, *transforms):
return reduce(lambda value, func: func(value), transforms, data)
def double(x):
return x * 2
def add_one(x):
return x + 1
def to_string(x):
return f"Result: {x}"
if __name__ == "__main__":
initial = 5
result = pipe(initial, double, …
How to Return Multiple Values from a Python Function
This code demonstrates how a Python function can return multiple values as a tuple, and how to unpack that tuple into individual variables.
def get_user_stats(name, score, level):
"""Return multiple values as a tuple."""
return name, score, level
if __name__ == "__main__":
result = get_user_stats("Alice", 95, 3)
print(result)
print(type(result))
# Unpacking into individual variables
player_name, player_score, player_level…
How to Sort a List of Numbers in Python with Default Parameters
Define a reusable sort function that uses a default parameter to sort a list of numbers in ascending or descending order.
def sort_numbers(numbers, reverse=False):
"""Sort a list of numbers in ascending or descending order."""
return sorted(numbers, reverse=reverse)
def main():
numbers = [5, 2, 9, 1, 7, 3]
# Default sort (ascending)
ascending = sort_numbers(numbers)
print(f"Ascending: {ascending}")
…
How to Use *args and **kwargs in Python Functions
Implement a variadic function that accepts arbitrary positional and keyword arguments using *args and **kwargs.
def display_info(title, *args, **kwargs):
"""Display positional and keyword arguments received."""
print(f"Title: {title}")
print(f"Additional positional args ({len(args)}):")
for i, arg in enumerate(args, 1):
print(f" {i}. {arg}")
print(f"Keyword args ({len(kwargs)}):")
for key, value…
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", "?")
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…
How to Use Default Parameters in Python Functions
Define a Python function with default parameters and call it using positional and keyword arguments.
def greet(name, greeting="Hello", punctuation="!"):
"""Concatenate a greeting message with default parameters."""
return f"{greeting}, {name}{punctuation}"
if __name__ == "__main__":
print(greet("Alice")) # Uses both defaults
print(greet("Bob", "Hi")) # Uses default punctua…
How to Use Default Parameters in Python Functions
Create a simple function with default parameters to build flexible, reusable greetings in Python.
def greet(name, greeting="Hello", punctuation="!"):
"""Return a personalized greeting message."""
return f"{greeting}, {name}{punctuation}"
if __name__ == "__main__":
print(greet("Alice"))
print(greet("Bob", "Hi"))
print(greet("Charlie", greeting="Hey", punctuation="?"))…
How to Use Default Parameters with Python's Split Function
Create a reusable Python wrapper around str.split with sensible default parameters for delimiter and maxsplit, showing beginners how default arguments work.
def split_with_defaults(text, delimiter=" ", maxsplit=-1):
"""
Split a string into parts using a delimiter.
Default behavior: split on spaces, unlimited splits.
"""
parts = text.split(delimiter, maxsplit)
return parts
if __name__ == "__main__":
# Example usage with defaults and custom par…
How to Use Keyword-Only Arguments in Python Functions
Define Python functions with keyword-only arguments using the * separator to enforce clarity and prevent positional misuse.
def greet(name, *, greeting="Hello", punctuation="!"):
"""Greet someone with a customizable message using keyword-only arguments."""
message = f"{greeting}, {name}{punctuation}"
return message
if __name__ == "__main__":
# Basic call with only the positional argument
print(greet("Alice"))
# Al…
How to Use Lambda Sorting Keys in Python
Learn to sort lists of dictionaries using lambda functions as key arguments in Python's sorted() method.
# Demonstrate lambda as a sorting key function
students = [
{"name": "Alice", "grade": 88},
{"name": "Bob", "grade": 92},
{"name": "Charlie", "grade": 75},
{"name": "Diana", "grade": 95}
]
# Sort by grade (ascending) using a lambda key
sorted_by_grade = sorted(students, key=lambda student: student["g…
How to Use a Dispatch Table in Python (Map Strings to Functions)
Maps string command names to callable functions in a dictionary, then dispatches calls safely with error handling.
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
raise ValueError("Division by zero")
return a / b
dispatch = {
"add": add,
"subtract": subtract,
"multiply": multiply,
"divide": divide,
}
def…
How to Use functools.reduce in Python
Apply functools.reduce with operator functions and lambda expressions to aggregate lists into sums, products, maximums, and concatenated strings.
from functools import reduce
import operator
# Sum all numbers in a list using reduce
numbers = [1, 2, 3, 4, 5]
sum_result = reduce(operator.add, numbers)
# Find the maximum value using reduce
max_result = reduce(lambda a, b: a if a > b else b, numbers)
# Multiply all numbers using reduce
product_result = reduce(la…
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.