Lambda Functions
Tags: @lambda @functions
Lambda functions are small anonymous functions. They can take any number of arguments, but can only have one expression.
The general syntax is: lambda [arguments] : [expression]
# Example function - the normal way
def foo(x):
return x + 10
# Equivalent lambda form
foo = lambda x : x + 10
# In both cases, function can be called by:
>>> foo(5)
>>> 15
# We can also do multiple arguments:
foo = lambda a, b, c : a + b + c
# This adds up a + b + c
>>> foo(1,2,3)
>>> 6
Use cases
You can use lambda functions inside other functions.
def foo(n):
return lambda x : x * n
# Now you can do this to made a function that doubles the number
bar = foo(2)
# which will do
>>> bar(10)
>>> 20
# Or if you want a function to triple the number, do:
bar2 = foo(3)
# which does
>>> bar2(10)
>>> 30