Lambda Functions

Date: February 22nd 2016
Last updated: February 22nd 2016

Lambda functions (aka anonymous functions) let you define a function as a "one-liner". You might use a lambda function in place of defining a "normal" function. Lambdas are useful in conjunction with filter, map and reduce.

A simple example

square_my_number = lambda x: x**2
square_my_number(4)
#16

# note lambda is a function
square_my_number
#<function <lambda> at 0x7f9540c17488>

Assignment example

# This is basically a nested function
# and has the same feel as a decorator: 
def exponent_function(n): return lambda x: x**n

exponent_function(2)
#<function counter.<locals>.<lambda> at 0x7f953ed0bc80>

ef = exponent_function(2)
ef.__name__
#'<lambda>'
# nothing in the dictionary
ef.__dict__
#{}
ef.__class__.__name__
#'function'
ef(3)
#6

# Make it cubed
ef3 = exponent_function(3)
ef3(3)
#9

Map reduce and filter examples

# use lambda to square all values of a list
a_list = [1, 2, 4, 5, 9, 5, 4, 2, 1]

# map
map(lambda x: x**2, a_list)
#[1, 4, 16, 25, 81, 25, 16, 4, 1]

# filter (removes elements by condition)
filter(lambda x: x % 2, a_list)
#[1, 5, 9, 5, 1]

# reduce (add up the values of a list)
# note this works from left to right in a_list
reduce(lambda x, y: x+y, a_list)
#33

# additional examples  
# Note that ifelse not required to filter out all numbers less than 5
filter(lambda x: x >=5, a_list)
#[5, 9, 5]

results matching ""

    No results matching ""