DEV Community

Discussion on: what are lambda functions in python

Collapse
 
val_baca profile image
Valentin Baca

A lambda is an anonymous function. Let's break down what that means:

first, you know what a function is: input, output. Going back to math a function 'f' could be defined as:

This is not python. This is math.
f(x) = x*x

Make for a simple python function:

def f(x):
  return x * x

x is the input and the output is x-squared and the name of the function is f.

Turns out if you rename 'f' to anything, like 'g' or 'whositwhatsit', it doesn't matter, it's still the same.

So if it can be called anything and we are never going to need its name, then we can just call it nothing: it's anonymous. this is indicated by the 'lambda' keyword.

# this is python, but it looks a lot like the math from before
lambda x : x * x
# this ^ x is the input. Can have more inputs separated by commas
# the colon ':' separates the input variables with the output
# the output is the result of what's to the right, in this case 'x*x'

# this defines the same lambda
# the name of the variables doesn't matter much either as long as it's consistent
lambda side : side * side

# Though x and y are common, make sure it's obvious from the variables what's going on

This is typically done with things that accept a function and do something with it. An example is 'map' which takes a list and a lambda, it applies the lambda to each item in the list, and returns the list of all the outputs

squares = map(lambda x : x * x, [0, 1, 2, 3, 4])

Finally, you can actually assign a lambda to a variable if it makes it easier or you need to reuse the lambda.

f = lambda x : x * x
squares = map(f, [0, 1, 2, 3, 4])
# squares will be [0, 1, 4, 9, 16]

big_squares = map(f, [100, 2000, 30000])
# big_squares will be [10000, 4000000, 900000000]

More info: python-course.eu/lambda.php