Functions & basics
Reusable building blocks — parameters, returns, scope, and clear function design.
Benchmark list append vs comprehension in Python
This micro-benchmark compares the speed of building a list with a for loop and append versus a list comprehension, using the timeit module to get precise timings.
import timeit
# Build a list of the first 1,000,000 integers using append in a loop
def append_loop(n=1_000_000):
result = []
for i in range(n):
result.append(i)
return result
# Build the same list using a list comprehension
def comprehension(n=1_000_000):
return [i for i in range(n)]
if __n…
Create a retry decorator with max attempts in Python
A decorator that retries a function up to a specified number of times when it raises an exception, with an optional delay between attempts.
import functools
import time
def retry(max_attempts, delay=0.1):
"""Retry a function up to max_attempts times on exception."""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(1, max_attempts + 1):
try:
…
How to Create Generator Functions with yield in Python
Create a memory-efficient generator function using yield to produce a Fibonacci sequence up to a limit.
def fibonacci_sequence(limit):
"""Generate Fibonacci numbers up to a given limit."""
a, b = 0, 1
while a <= limit:
yield a
a, b = b, a + b
if __name__ == "__main__":
fib_gen = fibonacci_sequence(100)
for number in fib_gen:
print(number, end=" ")
print()
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 Validate CLI Integer Option Within a Range in Python
Use argparse with integer type and bounds checking to validate a command-line option falls within a specified min-max range.
import argparse
def main():
parser = argparse.ArgumentParser(description="Validate an integer within a range.")
parser.add_argument("--value", type=int, required=True, help="Integer to validate")
parser.add_argument("--min", type=int, default=0, help="Minimum allowed value")
parser.add_argument("--max…
Sort a List of Dictionaries by Key in Python
Uses a lambda function with sorted() to order a list of dictionaries by a specified key, like price.
def get_items():
return [
{"name": "apple", "price": 3},
{"name": "banana", "price": 1},
{"name": "cherry", "price": 2},
]
if __name__ == "__main__":
items = get_items()
sorted_items = sorted(items, key=lambda item: item["price"])
for item in sorted_items:
print(f"{…
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.