Python

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)
16

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)
16

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s