Python Lesson 19: Lambda Functions

  1. Create a lambda function

Anonymous functions in Python are called Lambda functions. Typical functions are in Python are defined using the def keyword. Anonymous functions are defined using the lambda keyword. 

1) Create a lambda function


addFive = lambda x:x+5
addFive(10)
Notebook Output

2) Use a lambda function within the map function

Lambda functions are typically used with the built in functions map() and filter(). The map() function can be used to apply the lambda function to every item on an iterable. (list, tuple, etc..). 


myvalues = [1,2,3,4,5,6,7,8,9,10]
#create a new list by adding 5 to all items in the list
newvalues = list(map(lambda x:x+5,myvalues))
print(newvalues)
Notebook Output

3) Use a lambda function within the filter function

The filter function can be used to create an iterable based on true values in the lambda.  


myvalues = [1,2,3,4,5,6,7,8,9,10]
#create a new list with only even numbers
newvalues = list(filter(lambda x:(x%2 == 0),myvalues))
print(newvalues)
Notebook Output