9  Functional Programming

import sys
sys.version
'3.10.6 | packaged by conda-forge | (main, Aug 22 2022, 20:41:22) [Clang 13.0.1 ]'

9.1 List comprehension

Construct a simple list:

a = [1, 2, 3, 4, 5, 6, 7, 8, 9]

Or using range():

a = list(range(1, 10))
a
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Get squares of all even numbers in a:

b = [x**2 for x in a if x%2 == 0]
b
[4, 16, 36, 64]

Get the squares and cubes of all odd numbers in a:

c = [[x**2, x**3] for x in a if x%2 == 1]
c
[[1, 1], [9, 27], [25, 125], [49, 343], [81, 729]]

9.2 map()

a = list(range(1, 10))
a
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Triple each element of a:

b = list(map(lambda x: x * 3, a))
b
[3, 6, 9, 12, 15, 18, 21, 24, 27]

Get the square of all even numbers and the cube of all odd numbers in a:

c = list(map(lambda x: x**2 if x % 2 == 0 else x**3, a))
c
[1, 4, 27, 16, 125, 36, 343, 64, 729]

9.3 filter()

Keep all even numbers in a:

even = list(filter(lambda x: x%2 == 0, a))
even
[2, 4, 6, 8]