DEV Community

Mark Harless
Mark Harless

Posted on

What Are Lambda Expressions?

So far, in my early programming career, Python has been my favorite language to learn and write. It can be as simple or as complex as you want it to be. I would strongly recommend anyone who is interested in coding to first try Python because it is very readable. You won't waste your time memorizing the arcane syntax that other languages have. With that being said, let's talk about Lambda Expressions!

Your task is to create a function that squares a number. So you write the function and test it:

def square(x):
  return x * x

f(5)
25
Enter fullscreen mode Exit fullscreen mode

Your code is easy to read and, most importantly, it works. Passing any integer argument into the function square will return the desired output. Now, let's rewrite the same function as a Lambda Expression also known as anonymous or nameless functions:

square = lambda x: x * x

f(5)
25
Enter fullscreen mode Exit fullscreen mode

As you can see above, our output is correct and remains the same, however, we had to assign it to the variable f in order to use it.

The basics of writing a Lambda Expression is simple. It will always start with the keyword lambda followed by any number of arguments. Remember, it is perfectly okay for a Lambda Expression (or any function) to receive zero arguments. It is then followed by a colon : and finally, you enter a single expression. This expression is the return value. You cannot use multiline expressions in a Lambda.

Let's now see a Lambda Expression with more than one argument. This function will simply return the sum of the two integers.

sum = lambda x, y: x + y

sum(2, 3)
5
Enter fullscreen mode Exit fullscreen mode

As you can see, Lambdas are great for one-line expressions. It's also arguable that it is easier to read than a normal Python function. In my next blog post, I'll teach you the true power of Lambda Functions by passing them into other functions. This is called functional programming.

Top comments (0)