Python Map, Filter, Zip and Reduce by examples
These functions can save you a lot of time when working with iterables ,e.g Sets, Lists, Strings etc.
MAP
- Example 1
- Say you want to perform a min-max normalization all entries in your list
Syntax: map( function, iterable(s) )
arr = [ 32,11,55,21,9]normal = map( lambda x: (x - min(arr))/ (max(arr) -min(arr)), arr)normal = list(normal)// Output: [0.5, 0.043478260869565216, 1.0, 0.2608695652173913, 0.0]
- Note that in this case, we used a lambda function that applies our normalization formula to each element in the list.
Filter
Use filter to extract values that meet certain conditions in an iterable.
- Example 1
- Say you want to return all even values in a list
list_ = [4,7,9,1]even_vals = filter( lambda x: x % 2 == 0, list_ )event_vals = list(even_vals)// Outputs: [ 4 ]
- Note: You can also apply filter to more than one iterable if required.
ZIP
- With zip you can combine multiple iterables into one data structure
- Example
- Map player names to their scores in the last two games
names = [ “Ja”, “Beel”, “Madison”]last_game = [1,4,9]previous_game = [3,4,5]player_performance = list( zip( names, last_game, previous_game ) )// Output: ('Ja', 1, 3), ('Beel', 4, 4), ('Madison', 9, 5)]
- The elements with the same index are grouped together
Reduce
- Reduce allows you to perform cumulative tasks on your iterables.
- Example
- Calculate the product of all entries in a list
list_b = [ 1,3,2,5]product = reduce( lambda a, b: a* b , list_b)// product >> 30