Instantly share code, notes, and snippets.

# Atlas7/map_filter_reduce.mdSecret Last active Jul 13, 2017

What is the equivalent of JavaScript map, filter, and reduce in Python?

When I code in JavaScript (ES6/7+), I very often use the three functions `map()`, `filter()`, and `reduce()` - in the manipulation of an array (iterable). Master these three functions and we could (almost) perform any kind of operations - in particular, turn an array / list into something else.

I recently have to code hevily in Python 3 - the first thing I did was to hunt down the (more or less) equivalent for these three functions. Let's check this out.

# Map

Turn an array / list into something else.

## Problem to solve

Input: a list that looks like this:

``````[100, 200, 300]
``````

Output: an array of JavaScript Maps (objects) or a Python Dictionaries that looks like this:

``````// [
//   { index: 0, value: 101 },
//   { index: 1, value: 201 },
//   { index: 2, value: 301 }
// ]
``````

## JavaScript Solution

```a = [100, 200, 300].map(
(element, index) => ({'index': index, 'value': element+1})
)

// [
//   { index: 0, value: 101 },
//   { index: 1, value: 201 },
//   { index: 2, value: 301 }
// ]```

## Python Solution

Use list comprehension:

```a = [
{'index': index, 'value': element+1 }
for index, element in enumerate([100, 200, 300])
]

# [
#   {'value': 101, 'index': 0},
#   {'value': 201, 'index': 1},
#   {'value': 301, 'index': 2}
# ]```

# Filter

Subset an array / list.

## Problem to Solve

Say we have a list input:

``````[100, 200, 300]
``````

We want to output a list when the value is 100, or index is 2

``````[100, 300]
``````

## JavaScript Solution

```a = [100, 200, 300].filter(
(element, index) => (element === 100 || index === 2)
)

// [ 100, 300 ]```

## Python Solution

Use list comprehension:

```a = [
element for index, element in enumerate([100, 200, 300])
if (element == 100 or index == 2)
]

# [100, 300]```

# Reduce

Turn a list into an aggregated element

## Problem to solve

Say my input is a list:

``````[100, 200, 300]
``````

The desired output is the sum of all the elements:

``````600
``````

## JavaScript Solution

```a = [100, 200, 300].reduce(
(thisVal, nextVal) => (thisVal + nextVal)
)

// 600```

## Python Solution

Use reduce from functools library:

```from functools import reduce
a = reduce(
lambda thisVal, nextVal: thisVal + nextVal,
[100, 200, 300]
)

# 600```

In Python we could also use the Python built-in `map` and `filter` functions. This Python Tips page has some handy examples. One thing I've noticed about the Python map and filter functions though, is that they only enable you to get the element value, and not the element index. List comprehension enables you to select both the element value and index via the `enumerate` function.