filter and map functions also perform filtering and mapping.filter Function¶numbers = [10, 3, 7, 1, 9, 4, 2, 8, 5, 6]
def is_odd(x):
"""Returns True only if x is odd."""
return x % 2 != 0
list(filter(is_odd, numbers))
filter’s first argument must be a function that receives one argument and returns True if the value should be included in the result. filter returns an iterator, so filter’s results are not produced until you iterate through them—lazy evaluation. [item for item in numbers if is_odd(item)]
lambda Rather than a Function¶is_odd that return only a single expression’s value, you can use a lambda expression (or simply a lambda) to define the function inline. list(filter(lambda x: x % 2 != 0, numbers))
lambda keyword followed by a comma-separated parameter list, a colon (:) and an expression. lambda implicitly returns its expression’s value. numbers
list(map(lambda x: x ** 2, numbers))
map’s first argument is a function that receives one value and returns a new value.[item ** 2 for item in numbers]
filter and map¶list(map(lambda x: x ** 2,
filter(lambda x: x % 2 != 0, numbers)))
[x ** 2 for x in numbers if x % 2 != 0]
sum¶len, sum, min and max. functools module’s reduce function. ©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.
DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.