Day 4: Functional Programming
Tags: beginners, programming, python
Published: 2023-02-13 17:25:38



## What I learnt

- Reduce
- Lambda Expressions
- List Comprehension
- Set Comprehension
- Dictionary Comprehension

## Reduce

The reduce() function is defined in the functools module. It takes a function and a sequence as arguments, and returns a single value. The reduce() function is useful when you need to apply a function to an iterable and reduce it to a single cumulative value. The function can be found in the functools module and it takes two parameters:

> function : It is a function that is called with two arguments. function has to return a value.
> sequence : It is a sequence like list, tuple, etc.
> The reduce() function returns a single value.

Reduce is a method for combining an array of values into a single value. Reduce might, for example, be used to sum all the integers in an array or to concatenate all the strings in an array. To use reduce, you must first give a function that instructs reduce on how to combine the data. Two parameters will be supplied to the function: the current value and the next value. The function should return a single value that will be utilized in the reduction.

### Some Examples using Reduce

```python
- 1 - Using reduce to sum all the elements in a list

from functools import reduce
def add(x, y):
    return x + y

# print(reduce(add, [1, 2, 3, 4, 5]))


- 2 - Using reduce to concatenate all the elements in a list

def concat(x, y):
    return x + y

# print(reduce(concat, ['a', 'b', 'c', 'd', 'e']))


- 3 - Using reduce to find the maximum element in a list


def find_max(x, y):
    return x if x > y else y

# print(reduce(find_max, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))


- 4 - Using reduce to find the minimum element in a list


def find_min(x, y):
    return x if x < y else y

# print(reduce(find_min, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
```

## Lambda Expressions

Lambda functions are annonymous functions that are only used once within the code. They are also called as anonymous functions because they are not declared in the standard manner by using the def keyword. You can use the lambda keyword to create small anonymous functions.

> Syntax: lambda arguments : expression

The expression is executed and the result is returned:
Lambda functions are annonymous functions that are only used once within the code.

> > Lambda can be used with built-in functions like filter(), map() and reduce().

### Example

```python

test_scores = [73, 20, 65, 19, 76, 100, 88]
exam_scores = [12, 4, 9, 14, 16, 19]


1: Use lambda on a map to multiply scores

multiply_scores = list(map(lambda score: score \* 2, test_scores))

print('Multiplied Scores', multiply_scores)

# 2: Add multiple list using

add_scores = tuple(map(lambda exam_score, test_score: exam_score +
test_score, exam_scores, test_scores))
print('Added Scores', add_scores)

# 3: Get the squared value of the list

items = [5, 4, 3, 2]
squared_list = list(map(lambda item: item\*\*2, items))
print('Squared List', squared_list)

# 4: Use lambda to filter through a list of scores

filter_scores = list(filter(lambda score: score < 50, exam_scores))
print('Filtered Scores =>', filter_scores)

# 5 Sorting list of tuple with lambda

my_list = [(0, 2), (4, 3), (10, -1), (9, 9)]

my_list.sort(key=lambda item: item[1])
print('Sorted List', my_list)
```

## List Comprehensions

This is used to create a new list from an existing list. It is a more concise way to create a new list from an existing list. It is also more readable and faster than using a for loop to create a new list.

> The format is:

    [param for param in iterable]
    [char for char in 'comprehension']

> NOTE: I'd suggest you set your list comprehension into a discriptive function name. This will help you understand what the code is doing.

### Example of List Comprehension

```python
numb_range = [num for num in range(0, 26)]  # Prints a list of number from 0-25
num_multiple = [num**2 for num in range(0, 11)]
print(num_multiple)

# Print using Conditions
# The format is: [param for param in iterable if condition]


def is_even():
    even_num = [num**2 for num in range(0, 11) if num % 2 == 0]
    return even_num


print('Even Number', is_even())

users = [{'username': 'Jobizil', 'email': 'jobizil@email.com', 'age': 26},
         {'username': 'Lauren', 'email': 'lauren@email.com', 'age': 23},
         {'username': 'Quill', 'email': 'quill@email.com', 'age': 20},
         {'username': 'Luna', 'email': 'luna@email.com', 'age': 15},
         {'username': 'Jane', 'email': 'jane@email.com', 'age': 18}]

# Get users by email
user_email = [item['email'] for item in users]
print('User Email', user_email)

# Get users by age older than 20
user_age = [item['age'] for item in users if item['age'] >= 20]

print('User Age', user_age)
```

## Dictionary Comprehensions

This is used to create a new dictionary from an existing dictionary. It is a more concise way to create a new dictionary from an existing dictionary. It is also more readable and faster than using a for loop to create a new dictionary.
The format is: {key:value for (key,value) in iterable}

### Example

```python
user = {'user1':
        {'username': 'Quill',
         'email': 'quill@email.com',
         'age': 25,
         'color': 'red',
         'is_active': False,
         'is_admin': False,
         'is_staff': True},
        'user2':
        {'username': 'Jobizil',
         'email': 'jobizil@email.com',
         'age': 15,
         'color': 'blue',
         'is_active': True,
         'is_admin': True,
         'is_staff': False,
         }}
user_profile = {key: value for key, value in user.items()}


def get_user_by_age():
    profile_age = {key: value
                   for key, value in user.items() if value['age'] < 20}
    return profile_age


print('User Profile', user_profile)
print('Profile Age', get_user_by_age())
```

## Set Comprehensions

This is used to create a new set from an existing set. It is a more concise way to create a new set from an existing set. It is also more readable and faster than using a for loop to create a new set.

> The format is:

    {param for param in iterable}

### Example

    ```python
    num_set = {num for num in range(0, 11)}
    print(num_set)
    ```

## Conclusion

We've covered the fundamentals of Python comprehensions in this post. List comprehensions, dictionary comprehensions, and set comprehensions have all been addressed. We've also spoken about lambda expressions and reduce functions. I hope you found this information interesting. If you have any questions, please feel free to ask in the comments section below.

## References
To learn more about functional programming, check out the python documentation on functional programming [here](https://docs.python.org/3/howto/functional.html).