Skip to content

Instantly share code, notes, and snippets.

@Atlas7
Last active July 13, 2017 17:15
Show Gist options
  • Save Atlas7/c9dd475708b7d31d87759df222d3911e to your computer and use it in GitHub Desktop.
Save Atlas7/c9dd475708b7d31d87759df222d3911e to your computer and use it in GitHub Desktop.
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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment