Home > Backend Development > Python Tutorial > How Did `filter`, `map`, and `reduce` Change from Python 2 to Python 3?

How Did `filter`, `map`, and `reduce` Change from Python 2 to Python 3?

Mary-Kate Olsen
Release: 2024-12-01 20:42:11
Original
963 people have browsed it

How Did `filter`, `map`, and `reduce` Change from Python 2 to Python 3?

Evolution of filter, map, and reduce in Python 3

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template