Lambda
• Sometimes you need a simply arithmetic function
• Its silly to write a method for it, but redundant not too
• With lambda we can create quick simple functions
• Facts
– Lambda functions can only be comprised of a single
expression
– No loops, no calling other methods
– Lambda functions can take any number of variables
Syntax:
lambda param1,…,paramn : expression
1
Lambda Syntax
lambda.py
1 #Example 1
2 square_func = lambda x : x**2
3 square_func(4) #return: 16
4
5
6
7 #Example 2
8 close_enough = lambda x, y : abs(x – y) < 3
9 close_enough(2, 4) #return: True
0
1
2
3
2
Higher-Order Functions
• A higher-order function is a function that takes another function as
a parameter
• They are “higher-order” because it’s a function of a function
• Examples
– Map
– Filter
3
Filter
filter(function, iterable)
• The filter runs through each element of iterable (any iterable
object such as a List or another collection)
• It applies function to each element of iterable
• If function returns True for that element, then the element is
put into a List.
4
Filter Example
Example
1 nums = [0, 4, 7, 2, 1, 0 , 9 , 3, 5, 6, 8, 0, 3]
2
3 nums = list(filter(lambda x : x != 0, nums))
4
5 print(nums) #[4, 7, 2, 1, 9, 3, 5, 6, 8, 3]
6
5
Map
map(function, iterable, ...)
• Map applies function to each element of iterable and creates a
list of the results
• You can optionally provide more iterables as parameters to map
and it will place tuples in the result list
• Map returns an iterator which can be cast to list
6
Map Example
Example
1 nums = [0, 4, 7, 2, 1, 0 , 9 , 3, 5, 6, 8, 0, 3]
2
3 nums = list(map(lambda x : x % 5, nums))
4
5 print(nums)
6 #[0, 4, 2, 2, 1, 0, 4, 3, 0, 1, 3, 0, 3]
7