Skip to main content

Posts

Showing posts with the label map

Map, Filter and Reduce in Python

  Learning Sections          show Map, Filter, and Reduce in Python Python provides three powerful functions for functional programming: map() , filter() , and reduce() . These functions allow for efficient and readable data processing operations on iterables. 1. map() The map() function applies a given function to all items in an input list (or any other iterable) and returns an iterator of the results. Example: # Define a function to square a number def square ( x ): return x ** 2 numbers = [ 1 , 2 , 3 , 4 , 5 ] squared_numbers = map ( square , numbers ) print ( list ( squared_numbers )) # Output: [1, 4, 9, 16, 25] 2. filter() The filter() function constructs an iterator from elements of an iterable for which a function returns true. Example: # Define a function to check if a number is even def is_even ( x ): return x % 2 == 0 numbers = [ 1 , 2 , 3 , 4 , 5 ] even_num...