Python 3: Variations in the Implementation of Filter, Map, and Reduce
In Python 2, filter, map, and reduce behave differently from their Python 3 counterparts. This stems from several significant changes implemented in Python 3:
Views and Iterators Over Lists:
Removal of reduce():
Example Usage:
The Python 2 code snippets can be updated for Python 3 as follows:
def f(x): return x % 2 != 0 and x % 3 != 0 # **Filter:** Use list() to obtain a list of filtered values filtered_list = list(filter(f, range(2, 25))) # **Map:** Similarly, use list() to convert the iterator to a list cubed_list = list(map(lambda x: x ** 3, range(1, 11))) # **Reduce:** Use functools.reduce() or an explicit for loop from functools import reduce add_result = reduce(lambda x, y: x + y, range(1, 11)) print(filtered_list) # Output: [5, 7, 11, 13, 17, 19, 23] print(cubed_list) # Output: [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000] print(add_result) # Output: 55
Additional Resources:
The above is the detailed content of How Have `filter`, `map`, and `reduce` Changed in Python 3?. For more information, please follow other related articles on the PHP Chinese website!