One of Pythons most useful (and for beginners, confusing) tools is the lambda expression. lambda expressions allow us to create "anonymous" functions. This basically means we can quickly make ad-hoc functions without needing to properly define a function using def.
Function objects returned by running lambda expressions work exactly the same as those created and assigned by defs. There is key difference that makes lambda useful in specialized roles:
lambda's body is a single expression, not a block of statements.
Lets slowly break down a lambda expression by deconstructing a function:
In [1]:
def square(num):
result = num**2
return result
In [2]:
square(2)
Out[2]:
Continuing the breakdown:
In [3]:
def square(num):
return num**2
In [4]:
square(2)
Out[4]:
We can actually write this in one line (although it would be bad style to do so)
In [5]:
def square(num): return num**2
In [6]:
square(2)
Out[6]:
This is the form a function that a lambda expression intends to replicate. A lambda expression can then be written as:
In [7]:
lambda num: num**2
Out[7]:
Note how we get a function back. We can assign this function to a label:
In [8]:
square = lambda num: num**2
In [9]:
square(2)
Out[9]:
In [13]:
even = lambda x: x%2==0
In [14]:
even(3)
Out[14]:
In [15]:
even(4)
Out[15]:
In [22]:
first = lambda s: s[0]
In [23]:
first('hello')
Out[23]:
In [24]:
rev = lambda s: s[::-1]
In [25]:
rev('hello')
Out[25]:
In [17]:
adder = lambda x,y : x+y
In [19]:
adder(2,3)
Out[19]:
lambda expressions really shine when used in conjunction with map(),filter() and reduce(). Each of those functions has its own lecture, so feel free to explore them if you're very interested in lambda.
I highly recommend reading this blog post at Python Conquers the Universe for a great breakdown on lambda expressions and some explanations of common confusions!