= list(map(lambda x: x + 1, range(1, 6)))
result result
[2, 3, 4, 5, 6]
{purrr}
Functional programming in Python, compared to {purrr}
package in R.
map()
In R, purrr::map()
applies a function to each element of a list and returns a list. In Python, the built-in map()
function achieves this.
R
:
library(purrr)
map(1:5, ~ .x + 1)
Python
:
= list(map(lambda x: x + 1, range(1, 6)))
result result
[2, 3, 4, 5, 6]
map2()
R
:
library(purrr)
map2(1:5, 6:10, ~ .x + .y)
Python
:
# Using map with zip
= list(map(lambda x, y: x + y, range(1, 6), range(6, 11)))
result result
[7, 9, 11, 13, 15]
pmap()
R
:
library(purrr)
pmap(list(1:3, 4:6, 7:9), sum)
Python
:
from itertools import starmap
# Using starmap with zip
= list(starmap(lambda x, y, z: x + y + z, zip(range(1, 4), range(4, 7), range(7, 10))))
result result
[12, 15, 18]
accumulate()
R
:
library(purrr)
accumulate(1:5, ~ .x + .y)
Python
:
from itertools import accumulate
import operator
# Using accumulate
= list(accumulate(range(1, 6), operator.add))
result print(result)
[1, 3, 6, 10, 15]
reduce()
R
:
library(purrr)
reduce(1:5, ~ .x + .y)
Python
:
from functools import reduce
# Using reduce
= reduce(lambda x, y: x + y, range(1, 6))
result print(result) # Output: 15
15
map()
In general, list comprehension is prefered, because
import timeit
= list(range(1, 100))
a
# Measure time for list comprehension
= timeit.timeit('[x + x for x in a]', globals=globals(), number=1000000)
time_list_comprehension
# Measure time for map() with lambda
= timeit.timeit('list(map(lambda x: x + x, a))', globals=globals(), number=1000000) time_itertools_map
print(f"List Comprehension: {time_list_comprehension} seconds")
List Comprehension: 1.560666334000416 seconds
print(f"itertools map: {time_itertools_map} seconds")
itertools map: 3.486959083005786 seconds