Home

7: Functional Programming

Functional programming is a paradigm behind writing and organizing our code.

FP is all about separation of concerns.

Functions operate on well-defined structures such as lists and dictionaries.

Map

my_list = [1,2,3] def multiply_by2(item): return item * 2 updated_list = list(map(multiply_by2, my_list)) # [2,4,6] print(my_list) #[1,2,3]

Note that you need to cast the map object to a list.

Filter

my_list = [1,2,3] def filter_lt3(item): return item < 3 updated_list = list(filter(filter_lt3, my_list)) # [1,2] print(my_list) # [1,2,3]

Zip

my_list = [1,2,3] people = ['a','b','c'] tuple_list = list(zip(my_list, people)) # [(1, 'a'), (2, 'b'), (3, 'c')] print(my_list) # [1,2,3]

It will zip lists together into a list of tuples.

Reduce

from functools import reduce my_list = [1,2,3] # This is operating as the accumulator def add_items(item1, item2): return item1 + item2 tuple_list = list(reduce(add_items, my_list, 0)) # [1,3,6]

It will zip lists together into a list of tuples.

Lambda Expressions

Anonymous functions that you only need once.

my_list = [1,2,3] list(map(lambda item: item * 2, my_list)) # [2,4,6]

If you wanted with more params, you need to pass them. For example, using a lambda with reduce:

from functools import reduce my_list = [1,2,3] tuple_list = list(reduce(lambda item1, item2: item1 + item2, my_list, 0)) # [1,3,6]

List Comprehensions

Comprehensions are a quick way to create a list, set or dictionary without iterate over lists.

For example:

# Without comprehensions my_list = [] for char in 'hello': my_list.append(char) print(my_list) # ['h', 'e', 'l', 'l', 'o'] # With comprehensions: [param for param in iterable] my_list = [char for char in 'hello'] my_list2 = [num for num in range(0, 100)] # list of [0, ..., 99] # With conditions my_list3 = [num * 2 for num in range(0, 100) if num % 2 == 0] # list of even numbers [0, ..., 198]

Comprehensions can get confusing, so note the trade-off.

Set and Dictionary Comprehensions

For sets, we simple change list notation [] to a set {}.

my_list = {char for char in 'hello'} my_list2 = {num for num in range(0, 100)} # set of {0, ..., 99} # With conditions my_list3 = {num * 2 for num in range(0, 100) if num % 2 == 0} # set of even numbers [0, ..., 198]

For dictionaries:

simple_dict = { 'a': 1, 'b': 2, } my_dict = {key:value**2 for key, value in simple_dict.items()} print(my_dict) # {'a': 1, 'b': 4} my_dict2 = {num:num*2 for num in [1,2,3]} print(my_dict2) # {1: 2, 2: 4, 3: 6}

Repository

https://github.com/okeeffed/developer-notes-nextjs/content/python/Learn-To-Code-With-Python-Course/7-Functional-Programming

Sections


Related