Python Built-In Higher-Order Functions Overview
Mapping Sequences with map()
The map() function constructs an iterator that applies a given function to each item of an iterable. It transforms the data structure by passing every element through a processing logic.
Conisder calculating the cubic value for a sequence of integers:
def cube(val):
return val ** 3
numbers = [1, 2, 3, 4, 5]
output_iterator = map(cube, numbers)
print(list(output_iterator))
Execution demonstrates the lazy evaluation characteristic common in Python 3.
[1, 8, 27, 64, 125]
Filtering Data with filter()
The filter() tool extracts elements satisfying a specific condition. It accepts a predicate function returning boolean values and an iterable, yielding only those items where the predicate evaluates to True.
Example scenario: isolating values divisible by 3 from a dataset.
def is_multiple_of_three(n):
return n % 3 == 0
source_data = [3, 6, 7, 9, 10, 12]
filtered_result = filter(is_multiple_of_three, source_data)
print(list(filtered_result))
Output:
[3, 6, 9, 12]
Combining Iterables with zip()
The zip() function aggregates elements from multiple iterables into tuples. Iteration stops once the shortest input sequence is exhausted.
Practical usage involves pairing identifiers with corresponding values:
ids = ['A', 'B', 'C']
scores = [85, 92, 78]
combined = zip(ids, scores)
for record in combined:
print(record)
Result:
('A', 85)
('B', 92)
('C', 78)
Source documentation indicates the class manages tuple generation internally until exhaustion occurs.
Tracking Indices with enumerate()
While iterating, enumerate() appends a counter to each item. This simplifies scenarios requiring position awareness alongside data access.
Configuration:
items = ['apple', 'orange', 'banana']
indexed_items = enumerate(items, start=1)
for index, value in indexed_items:
print(f"{index}: {value}")
Output:
1: apple
2: orange
3: banana
Optimizing Logic with Functional Patterns
Efficient problem-solving often benefits from functional constructs. A common optimization task is aggregating values matching specific criteria without explicit loops.
Task: Compute the total sum of even integers from 1 to 20.
Functional Approach:
total = sum(x for x in range(1, 21) if x % 2 == 0)
print(total)
Conventional Iterative Method:
accumulator = 0
for val in range(1, 21):
if val % 2 == 0:
accumulator += val
print(accumulator)
Both approaches yield identical results, demonstrating trade-offs between readability and explicit control flow.