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.
Turn an array / list into something else.
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 }
// ]
a = [100, 200, 300].map(
(element, index) => ({'index': index, 'value': element+1})
)
// [
// { index: 0, value: 101 },
// { index: 1, value: 201 },
// { index: 2, value: 301 }
// ]
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}
# ]
Subset an array / list.
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]
a = [100, 200, 300].filter(
(element, index) => (element === 100 || index === 2)
)
// [ 100, 300 ]
Use list comprehension:
a = [
element for index, element in enumerate([100, 200, 300])
if (element == 100 or index == 2)
]
# [100, 300]
Turn a list into an aggregated element
Say my input is a list:
[100, 200, 300]
The desired output is the sum of all the elements:
600
a = [100, 200, 300].reduce(
(thisVal, nextVal) => (thisVal + nextVal)
)
// 600
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.