Core Functional and Utility Functions in Python
Python provides a suite of built-in functions that are essential for functional programming, data transformation, and common operations. This article covers several key functions and their practical applications.
The filter() Function
The filter() function constructs an iterator from elements of an iterable for which a function returns true.
def is_positive(num):
return num > 0
result = list(filter(is_positive, [-5, -2, 0, 3, 7, -1]))
print(result) # Output: [3, 7]
# Using a lambda expression
nums = range(-5, 5)
filtered = list(filter(lambda n: n % 2 == 0, nums))
print(filtered) # Output: [-4, -2, 0, 2, 4]
The map() Function
The map() function applies a given function to every item of an iterable and returns an iterator of the results.
def calculate_area(radius):
return 3.14159 * radius * radius
radii = [1, 2, 3, 4]
areas = list(map(calculate_area, radii))
print(areas) # Output: [3.14159, 12.56636, 28.27431, 50.26544]
# Processing multiple iterables
list_a = [1, 2, 3]
list_b = [10, 20, 30]
combined = list(map(lambda x, y: x + y, list_a, list_b))
print(combined) # Output: [11, 22, 33]
The reduce() Function
The reduce() function, available in the functools module, cumulatively applies a function to items in a sequence, reducing it to a single value.
from functools import reduce
def multiply_values(a, b):
return a * b
product_result = reduce(multiply_values, [2, 3, 4, 5])
print(product_result) # Output: 120
# Calculating factorial
def factorial_calc(n):
return reduce(lambda x, y: x * y, range(1, n + 1))
print(factorial_calc(5)) # Output: 120
Sorting with sort() and sorted()
Python offers two primary methods for sorting: list.sort() sorts a list in-place, while sorted() returns a new sorted list from any iterable.
# Basic sorting
sample_list = [34, 12, 89, 5, 23]
sample_list.sort()
print(sample_list) # Output: [5, 12, 23, 34, 89]
original = [34, 12, 89, 5, 23]
new_sorted = sorted(original)
print(new_sorted) # Output: [5, 12, 23, 34, 89]
print(original) # Output: [34, 12, 89, 5, 23] (unchanged)
Both methods accept key and reverse parameters for custom sorting.
# Sorting with a key function
data_points = [('item2', 45), ('item1', 12), ('item3', 78)]
sorted_by_number = sorted(data_points, key=lambda x: x[1])
print(sorted_by_number) # Output: [('item1', 12), ('item2', 45), ('item3', 78)]
# Descending order
descending_sorted = sorted([5, 1, 9, 3], reverse=True)
print(descending_sorted) # Output: [9, 5, 3, 1]
Essential Mathematical Functions
abs(x): Returns the absolute value of a number.divmod(a, b): Returns a tuple containing quotient and remainder.pow(x, y[, z]): Returns x raised to the power y (modulo z if provided).round(x[, n]): Rounds a number to n digits after the decimal point.sum(iterable[, start]): Sums items of an iterable from left to right.
Collection and Type Conversion Functions
enumerate(iterable, start=0): Returns an enumerate object yielding pairs of index and value.zip(*iterables): Aggregates elements from multiple iterables into tuples.max(iterable[, key])/min(iterable[, key]): Returns the largest/smallest item.list(iterable),tuple(iterable),set(iterable),dict(): Construct corresponding data structures.str(object),int(x[, base]),float(x): Type conversion functions.
Boolean and Reflection Functions
all(iterable): Returns True if all elements are true (or iterable is empty).any(iterable): Returns True if any element is true.isinstance(object, classinfo): Checks object type against a class or tuple of classes.hasattr(object, name): Checks if an object has a named attribute.getattr(object, name[, default]): Returns the value of a named attribute.callable(object): Checks if an object appears callable.
I/O and Utility Functions
open(file, mode='r', buffering=-1, encoding=None): Opens a file and returns a file object.input([prompt]): Reads a line from input, converting it to a string.print(*objects, sep=' ', end='\\n', file=sys.stdout, flush=False): Prints objects to a text stream.len(s): Returns the number of items in a container.range(stop)orrange(start, stop[, step]): Generates a sequence of numbers.type(object): Returns the type of an object.dir([object]): Returns the list of names in the current local scope or attributes of an object.