In the transition from Python 2 to 3, the behavior of filter, map, and reduce underwent substantial changes.
Views and Iterators Instead of Lists
To promote efficiency, map and filter now return iterators instead of lists. For instance, in Python 2, filter(f, range(2, 25)) returned a list of the filtered values, while in Python 3, it returns an iterator. A simple fix is to convert the iterator to a list explicitly using list(map(...)), but a more elegant solution often involves list comprehensions or restructuring the code to eliminate the need for a list.
Removal of reduce
Python 3 removed the built-in reduce function. Instead, it recommends using functools.reduce if necessary. However, as the documentation notes, an explicit for loop is generally more readable and appropriate for 99% of cases.
Conclusion
These changes aimed to improve the efficiency and design of Python 3's built-in functions. By following the guidance provided in the documentation, developers can effectively utilize iterators and alternative approaches to achieve similar functionality to their Python 2 code in Python 3.
The above is the detailed content of How Did `filter`, `map`, and `reduce` Change from Python 2 to Python 3?. For more information, please follow other related articles on the PHP Chinese website!