Net-informations.com
SiteMap  | About    

How to use map, filter and reduce?

When working on Python programming you inevitably come across situations where you have to do some data manipulation. In most cases, you use control statements to get the desired result, but these control statements can quickly become a bit messy and large. Functional techniques can help you write more declarative code that is easier to understand at a glance, refactor, and test. Most of the times it can be much easier to use the map , filter or reduce methods.

The rule of thumb you use to determine which method you should use is as follows:

  1. If you already have a list of values and you want to do the exact same operation on each of the elements in the array and return the same amount of items in the list, in these type of situations it is better to use the map method.

  2. If you already have list of values but you only want to have items in the array that match certain criteria, in these type of situations it is better to use the filter method.

  3. If you already have list of values, but you want to use the values in that list to create something completely new, in these type of situations it is better to use the reduce method.

Map

Map operation takes a mapping function and a vector of data as arguments and returns a new vector, which is the result of applying the mapping function on each element of the vector independently. The returned value from map() (map object) then can be passed to functions like list() (to create a list), set() (to create a set) and so on.

Syntax

  1. function_to_apply - map() passes each item of the iterable to this function.

  2. list_of_inputs - iterable which is to be mapped

example

output

Most of the times map function use lambdas.

output

or

output

Filter

The filter function operates on a list and returns a subset of that list after applying the filtering rule.

example

output

Reduce

The reduce function will transform a given list into a single value by applying a given function continuously to all the elements. It basically keeps operating on pairs of elements until there are no more elements left.

The following example shows how to find the product of given numbers.

output

Using Reduce method:

output









net-informations.com (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.