The python lambda

Recently I learned how to use the lambda function, a simple, unbound one liner function. A lambda is similar to a normal Python function, the only difference is in the way it is used. The example below will explain better:

def poww(x):
    return x ** 2

>>> poww(4)

The poww function defined above takes an argument x and squares it. So if we were to call the poww function and pass in the value 4 to it, the return value would be 16.

OK, good and well, let’s try this using lambda:

(lambda i: i ** 2)(4)

The lambda looks odd, but it is no different from the function we defined above, the “i” in the lambda function represents the argument you pass in and the part on the right of the “:” is what gets returned.

The lambda is ideal for when you need a function that will do something once and be discarded.