Home >Backend Development >Python Tutorial >How Have `filter`, `map`, and `reduce` Changed in Python 3?

How Have `filter`, `map`, and `reduce` Changed in Python 3?

Susan Sarandon
Susan SarandonOriginal
2024-11-27 15:38:10303browse

How Have `filter`, `map`, and `reduce` Changed in Python 3?

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:

  • map() and filter() now return iterators instead of lists. To obtain a list, explicitly convert them using list().

Removal of reduce():

  • reduce() has been removed from core Python in favor of the functools.reduce() function. However, an explicit for loop is typically more readable and preferred.

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:

  • [Python 3.0 Changes](https://docs.python.org/3/whatsnew/3.0.html)
  • [map() and Views](https://wiki.python.org/moin/Getting a map() to return a list in Python 3.x)

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!

Statement:
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