Functions & basics
Reusable building blocks — parameters, returns, scope, and clear function design.
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 Parse Function Signatures in Python with inspect
Extract a function's parameter names, kinds, defaults, annotations, and return type using Python's built-in inspect module.
import inspect
def example_function(a: int, b: str = "default", *args, c: float = 1.5, **kwargs) -> bool:
"""An example function with various parameter types."""
return True
def parse_signature(func):
"""Parse a function's signature using the inspect module."""
sig = inspect.signature(func)
param…
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 Dictionaries by Key with a Lambda in Python
Sort a list of dictionaries ascending or descending by one of their keys using sorted() with a lambda as the key function — a beginner-friendly pattern.
def get_students():
return [
{"name": "alice", "score": 85},
{"name": "bob", "score": 92},
{"name": "carol", "score": 78},
{"name": "dave", "score": 92},
]
students = get_students()
sorted_by_score = sorted(students, key=lambda s: s["score"])
print("Sorted by score (ascending)…
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 Python's next() Builtin with a Default Sentinel Value
A wrapper function that returns the next item from an iterator, or a default sentinel value when the iterator is exhausted.
def get_next_or_default(iterator, default=None):
"""Return the next item from an iterator, or default if exhausted."""
return next(iterator, default)
if __name__ == "__main__":
fruits = iter(["apple", "banana", "cherry"])
print(get_next_or_default(fruits)) # apple
print(get_next_or…
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 a Lambda Sort Key in Python
Sort a list of strings by length, then alphabetically, using a lambda function as the sorting key in Python.
def sort_words(words):
"""Sort words by length, then alphabetically using a lambda key."""
return sorted(words, key=lambda word: (len(word), word))
if __name__ == "__main__":
sample_words = ["apple", "kiwi", "banana", "fig", "cherry"]
result = sort_words(sample_words)
print("Original:", sampl…
How to Use a Lambda Sorting Key in Python
Sort a list of strings by their last letter using a lambda function as the sorting key.
def get_last_letter(word):
return word[-1]
words = ["banana", "apple", "cherry", "date", "elderberry"]
if __name__ == "__main__":
sorted_words = sorted(words, key=get_last_letter)
print(sorted_words)
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…
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.
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…
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.
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()}.")
Browse by section
Each section groups closely related Python snippets.
Functions & basics — Python code examples
What you will find here
This page collects functions & basics snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
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.