Reference library

Python Code Samples

Easy snippets you can copy, study, and run in the browser editor.

94 matches
Functions & basics easy

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.

higher-order functions composition
Python
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))
12 0 Open
Functions & basics easy

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.

functions default-parameters arguments
Python
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…
13 0 Open
Functions & basics easy

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.

docstrings documentation functions
Python
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.
 …
13 0 Open
Functions & basics easy

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.

list slicing functions
Python
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…
15 0 Open
Functions & basics easy

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.

functions default-parameters list
Python
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…
14 0 Open
Functions & basics easy

How to Parse Function Parameters with Defaults in Python

Create Python functions with default parameter values to make arguments optional and provide sensible fallbacks.

functions default-parameters arguments
Python
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…
14 0 Open
Functions & basics easy

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.

map filter callbacks
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)
16 0 Open
Functions & basics easy

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.

functions functional reduce
Python
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, …
13 0 Open
Functions & basics easy

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.

functions tuple return-values
Python
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…
16 0 Open
Functions & basics easy

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.

sorting default-parameters functions
Python
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}")
    
   …
13 0 Open
Functions & basics easy

How to Use *args and **kwargs in Python Functions

Implement a variadic function that accepts arbitrary positional and keyword arguments using *args and **kwargs.

args kwargs variadic
Python
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…
14 0 Open
Functions & basics easy

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.

functions default-parameters arguments
Python
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…
14 0 Open
Functions & basics easy

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.

functions parameters defaults
Python
def greet(name, greeting="Hello", punctuation="!"):
    message = f"{greeting}, {name}{punctuation}"
    print(message)

if __name__ == "__main__":
    greet("Alice")
    greet("Bob", "Hi")
    greet("Charlie", "Hey", "?")
13 0 Open
Functions & basics easy

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.

functions default-parameters comparison
Python
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…
13 0 Open
Functions & basics easy

How to Use Default Parameters in Python Functions

Define a Python function with default parameters and call it using positional and keyword arguments.

functions default-parameters arguments
Python
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…
13 0 Open
Functions & basics easy

How to Use Default Parameters in Python Functions

Create a simple function with default parameters to build flexible, reusable greetings in Python.

functions default-parameters basics
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="?"))…
14 0 Open
Functions & basics easy

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.

strings default-parameters functions
Python
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…
14 0 Open
Functions & basics easy

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.

functions keyword-arguments function-signature
Python
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…
15 0 Open
Functions & basics easy

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.

lambda sorting beginner
Python
# 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…
15 0 Open
Functions & basics easy

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.

dispatch-table dictionary functions
Python
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…
13 0 Open
Functions & basics easy

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.

reduce functools lambda
Python
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…
12 0 Open
Functions & basics easy

How to Use singledispatch for Type-Based Overloading in Python

This code demonstrates Python's functools.singledispatch decorator to create functions that behave differently based on the type of their first argument.

singledispatch overloading functools
Python
from functools import singledispatch

@singledispatch
def process(value):
    return f"Unknown type: {type(value).__name__}"

@process.register(int)
def _(value):
    return f"Integer: {value * 2}"

@process.register(str)
def _(value):
    return f"String: {value.upper()}"

@process.register(list)
def _(value):
    re…
12 0 Open
Functions & basics easy

How to Use the if __name__ == '__main__' Guard in Python

This code defines reusable functions and uses the standard main guard to run them only when the script is executed directly, not when imported.

main guard __main__ script entry point
Python
def greet(name: str) -> str:
    """Return a friendly greeting."""
    return f"Hello, {name}!"

def get_planet() -> str:
    """Return the name of our planet."""
    return "Earth"

if __name__ == "__main__":
    user = "Dorothy"
    print(greet(user))
    print(f"We live on {get_planet()}.")
13 0 Open
Functions & basics easy

How to Write a Normalize Function with Default Parameters in Python

Define a reusable normalize function with configurable default parameters for lowercase conversion, whitespace stripping, and punctuation removal.

functions default-parameters string-processing
Python
def normalize(text, lowercase=True, strip_whitespace=True, remove_punctuation=False):
    """Normalize a string based on configurable options."""
    if lowercase:
        text = text.lower()
    if strip_whitespace:
        text = text.strip()
    if remove_punctuation:
        text = ''.join(char for char in text if…
13 0 Open

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

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. 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.