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…
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 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 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 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 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 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 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 implement binary search in Python
Standalone binary search function that returns the index of a target in a sorted list, or -1 if not found.
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
if __name__ ==…
Python Filter Function with Default Parameters for Beginners
Create a reusable filter function with default parameters to keep or exclude numbers above or below a threshold.
def filter_numbers(numbers, threshold=0, reverse=False):
"""Return numbers that pass the threshold filter.
Args:
numbers: list of numbers to filter
threshold: minimum value to keep (default 0)
reverse: if True, keep numbers below threshold (default False)
"""
if reverse:
…
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.