result = list(map(lambda x: x + 1, range(1, 6)))
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:
result = list(map(lambda x: x + 1, range(1, 6)))
result[2, 3, 4, 5, 6]
map2()R:
library(purrr)
map2(1:5, 6:10, ~ .x + .y)Python:
# Using map with zip
result = list(map(lambda x, y: x + y, range(1, 6), range(6, 11)))
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
result = list(starmap(lambda x, y, z: x + y + z, zip(range(1, 4), range(4, 7), range(7, 10))))
result[12, 15, 18]
accumulate()R:
library(purrr)
accumulate(1:5, ~ .x + .y)Python:
from itertools import accumulate
import operator
# Using accumulate
result = list(accumulate(range(1, 6), operator.add))
print(result)[1, 3, 6, 10, 15]
reduce()R:
library(purrr)
reduce(1:5, ~ .x + .y)Python:
from functools import reduce
# Using reduce
result = reduce(lambda x, y: x + y, range(1, 6))
print(result) # Output: 1515
map()In general, list comprehension is prefered, because
import timeit
a = list(range(1, 100))
# Measure time for list comprehension
time_list_comprehension = timeit.timeit('[x + x for x in a]', globals=globals(), number=1000000)
# Measure time for map() with lambda
time_itertools_map = timeit.timeit('list(map(lambda x: x + x, a))', globals=globals(), number=1000000)print(f"List Comprehension: {time_list_comprehension} seconds")List Comprehension: 0.9625627920031548 seconds
print(f"itertools map: {time_itertools_map} seconds")itertools map: 2.9447722919867374 seconds