Sun 25 January 2015

Filed under Python


First: What is 'lambda'?

In very short, lambda is a one-line, mini function. So we just include the short code directly into that line of code instead of writing out a separate function for it. If that mini function would be used in several places in the code, then it still might pay to write a function for it.

For example: if we have to double a digit. Instead of writing a function to do that, we might write a quick lambda.

The Syntax

(lambda a: a *2)(6)

  • The lambda expression should be in parentheses ().

  • Starts off with the word lambda

  • And then the variable name, in this case a. There could be more than 1 variable.

  • And the colon :

  • And then the quick little code. In this case a * 2. The variable multiplied by 2.

  • And lastly an argument for this little lambda function. In this case (6). In its own parentheses. This is how we call the lambda function.

Another way to write a lambda

c = lambda a: a* 2

Here we are assigning the lambda function to c and then calling c(2). This sort of defeats the purpose. But it still saves some coding since you don't have to def or return.

A few more examples:

(lambda x: x <10)(11)

This lambda checks if 11 is less than 10. And in this case returns False.

(lambda x: x %2)(8)

This lambda checks if 8 is evenly divisible by 2. And in this case returns True.

(lambda x, y: x < y)(6, 7)

This lambda uses 2 variables - x and y. It compares if x is less than y. It compares if 6 < 7 and in this case returns True.

Lambdas get even cooler

Lambdas can be used with map, reduce and filter. Coming soon.

Comments © Dee Kras Powered by Pelican and Twitter Bootstrap. Icons by Font Awesome and Font Awesome More