Lambda Functions
Lambda functions are small, anonymous functions defined using the lambda keyword. They can take any number of arguments but can only have one expression. The syntax for a lambda function is:
lambda arguments: expression
# Traditional way
def double(x):
return x * 2
# Lambda way
double_lambda = lambda x: x * 2
print(double_lambda(10)) # 20
Higher-Order Functions
“Higher-Order” is just a function that hires another function to do a job.
map()
Use map() when you want to apply the same change to every single item in a list.
prices_usd = [10, 20, 30]
# Change every price to Euro (0.9 rate)
prices_eur = list(map(lambda p: p * 0.9, prices_usd))
print(prices_eur) # [9.0, 18.0, 27.0]
filter()
Use filter() when you want to keep some items and throw others away based on a rule (True/False).
scores = [45, 88, 92, 33, 67]
# Keep only scores that are 60 or higher
passing_scores = list(filter(lambda s: s >= 60, scores))
print(passing_scores) # [88, 92, 67]
Why do we need list()?
You’ll notice we wrap these in list(). This is because map and filter are lazy (just like the Generators we covered).
They don’t actually do the work until you ask for the result. If you don’t use list(), Python will just give you a “Map Object” (a promise to do the work later). Wrapping it in list() forces ‘em to finish the job so you can see the final product.
Lambda vs. List Comprehension
Modern Python developers usually prefer List Comprehensions because they are easier to read. However, map() and filter() are still very common in data science and functional programming.
# Map style:
squared = list(map(lambda x: x**2, [1, 2, 3]))
# List Comprehension:
squared = [x**2 for x in [1, 2, 3]]