Understanding the Evolution of Functional Tools in Python: filter, map, and reduce
In Python 3, the behavior of filter, map, and reduce functions has undergone significant changes compared to their counterparts in Python 2. This can lead to confusion for users accustomed to the previous syntax and behavior.
Changes to filter and map
In Python 3, both filter and map return iterators rather than lists. This is a result of the shift from producing concrete data structures to providing more efficient and memory-efficient views. If you need to obtain a list as the result, you can use the list() function to convert the iterator, e.g. list(filter(f, range(2, 25))). A better solution, however, is to consider list comprehensions or reworking the code to eliminate the need for a list.
Removal of reduce
Python 3 has removed the built-in reduce function. Instead, users should employ the functools.reduce function if required. However, it is important to note that in most cases, an explicit for loop provides a more readable and efficient alternative.
Example Code Modifications
To adapt the provided Python 2 code to Python 3, the following changes are necessary:
# Python 2 filter(f, range(2, 25)) map(cube, range(1, 11)) reduce(add, range(1, 11)) # Python 3 list(filter(f, range(2, 25))) list(map(cube, range(1, 11))) functools.reduce(add, range(1, 11))
Conclusion
By understanding these changes in Python 3, developers can avoid surprises and write code that effectively utilizes the functional tools available in the language.
The above is the detailed content of How Have Python\'s `filter`, `map`, and `reduce` Functions Changed in Python 3?. For more information, please follow other related articles on the PHP Chinese website!