Junior — Middle
How can functional tools in collections be used for data processing?
sobes.tech AI
Answer from AI
Functional tools in Python, such as map(), filter(), reduce(), and list comprehensions, allow for efficient processing of data collections without explicit loops.
map(function, iterable)applies the function to each element of the collection and returns an iterator with the results.filter(function, iterable)filters elements for which the function returnsTrue.reduce(function, iterable)(from thefunctoolsmodule) reduces the collection to a single value by applying the function sequentially.
Example:
from functools import reduce
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers)) # [1, 4, 9, 16, 25]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) # [2, 4]
sum_numbers = reduce(lambda x, y: x + y, numbers) # 15
Such tools make the code more concise and often improve readability when working with data.