8  Functional Programming

8.1 Compared to {purrr}

Functional programming in Python, compared to {purrr} package in R.

8.1.1 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]

8.1.2 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]

8.1.3 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]

8.1.4 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]

8.1.5 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: 15
15

8.2 List comprehension vs map()

In general, list comprehension is prefered, because

  1. Faster
  2. More Pythonic
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: 1.560666334000416 seconds
print(f"itertools map: {time_itertools_map} seconds")
itertools map: 3.486959083005786 seconds