You are on page 1of 20

Extending Functions

CC2 – Introduction to Computer Programming


Functional Programming in Python
• There are many other statements and features that can be used
when creating functions in Python.
• These are some of the functions and features that you can use:
• Lambda
• Map
• Reduce
• Filter
Lambda
• The lambda keyword creates an inline function that contains a
single expression.
• This is also called an inline/anonymous function.
• The value of this expression is what the function returns when
invoked.
• The basic syntax of lambda is as follows:
• function_name = lambda parameters:function_body
Lambda
• To use the lambda Function, let us consider this simple
function:
• def greeting():
• return "Hello"
• print(greeting()) # The output of this is “Hello”
• To convert it to lambda, this is how it would look like:
• greeting2 = lambda: "Hello"
• print(greeting2()) # Outputs “Hello”
Lambda
• You do not write return when creating a function with
lambda.
• The value after “:” is automatically returned.
• Lambdas can also take arguments:
• make_uppercase = lambda s : s.upper() # Makes a
string all uppercase
• make_lowercase = lambda s : s.lower() # Makes a
string all lowercase
• print(make_uppercase("Hello")) # Outputs HELLO
• print(make_lowercase("Hello")) # Outputs hello
Lambda
• lambda functions can also take an arbitrary number of
arguments/keyword arguments, like normal functions.
• An example of this is shown below:
• greetings = lambda x, *args, **kwargs: print(x,
args, kwargs)
• greetings('ronald mcdonald', 'burger king',
colonel='sanders') # outputs "ronald mcdonald
('burger king',) {'colonel': 'sanders'}"
Lambda
• One can also call other functions (with/without arguments)
from inside a lambda function.
• def printMsg(message):
• print(message)
• greeting = lambda x = "Hello, how are you?" :
printMsg(x)
• greeting() # Outputs "Hello, how are you?"
Map
• map takes a function and a collection of items.
• It makes a new, empty collection, runs the function on each item
in the original collection and inserts each return value into the
new collection.
• It then returns the new collection.
• This is the syntax of the map function:
• map(function_name, *iterables)
Map
• function_name is the function on which each element in
iterables would be applied on.
• The “*” on iterables means there can be as many
iterables as possible.
• Something to note is that in Python 2, the map() function
returns a list.
• In Python 3, the map() function returns a “map object” which
needs to be converted to a list with list().
Map
• Let's say you have a list of names that you would like to make
all uppercase, one way to do this is shown below:
• name_list = ['phil', 'perry', 'peter', 'paul']
• uppercase_names = []
• for name in name_list:
• names = name.upper()
• uppercase_names.append(names)
• print(uppercase_names) # Outputs "['PHIL', 'PERRY',
'PETER', 'PAUL']"
Map
• You can shorten your code with the use of map, as shown here:
• name_list = ['phil', 'perry', 'peter', 'paul']
• uppercase_names = list(map(str.upper, name_list))
• print(uppercase_names) # Outputs "['PHIL', 'PERRY',
'PETER', 'PAUL']"
Reduce
• reduce takes a function and a collection of items.
• It returns a value that is created by combining the items.
• It returns the sum of all the items in the collection.
• The syntax of reduce is shown below:
• reduce(func, iterable[, initial])
• Before using this code, it is necessary to use import to get the
needed code to run reduce:
• from functools import reduce
Reduce
• In the syntax func is the function on which each element in the
iterable gets cumulatively applied to.
• initial is the optional value that gets placed before the
elements of the iterable in the calculation.
• func requires two arguments, the first of which is the first
element in iterable (if initial is not supplied) and the second
element in iterable.
Reduce
• An example of reduce is shown below:
• from functools import reduce
• numbers = [5, 10, 15, 20, 25, 30]
• def custom_sum(first, second):
• return first + second
• result = reduce(custom_sum, numbers)
• print(result) # Outputs 105
Reduce
• So how does the code that was shown in the previous slide
work?
• reduce takes the first and second elements in numbers and passes
them to custom_sum respectively.
• custom_sum computes their sum and returns in to reduce.
• reduce then takes that results and uses it as the first element to
custom_sum and takes the next element (third) in numbers as the
second element to custom_sum.
• This repeats until numbers is exhausted.
Reduce
• What happens if we add an initial value to reduce?
• from functools import reduce
• numbers = [5, 10, 15, 20, 25, 30]
• def custom_sum(first, second):
• return first + second
• result = reduce(custom_sum, numbers, 15) # Added an
initial value of 15
• print(result) # Outputs 120
Reduce
• So, what happens to the code now that an initial value of 15 was
added?
• reduce now takes 15 as the first element and then takes the first value
in numbers in the second element and passes them to custom_sum.
• custom_sum computes their sum and returns in to reduce.
• reduce then takes that results and uses it as the first element to
custom_sum and takes the next element (second) in numbers as the
second element to custom_sum.
• This repeats until numbers is exhausted.
Filter
• filter takes a function and a collection.
• It returns a collection of every item for which the function
returned True.
• Filter requires the function to return Boolean values (True or
False) and then passes each element in the iterable through
the function.
• This is the syntax for filter:
• filter(func, iterable)
Filter
• Only one iterable is required for filter.
• The func argument is required to return a Boolean type.
• If it doesn’t return a Boolean type, filter returns the iterable
passed to it.
• func also must only take one argument.
• filter passes each element in the iterable through func
and returns only the ones that evaluate to true.
• Make sure to convert the output of filter to a list with
list().
Filter
• An example of how filter is used is shown below:
• grades = [60, 70, 40, 90, 88, 76, 75, 82, 83]
• def isGradePassed(grade):
• return grade >= 75
• gradeCheck = list(filter(isGradePassed, grades))
• print(gradeCheck) # Outputs "[90, 88, 76, 75, 82,
83]"

You might also like