카테고리
coding

Python def and lambda syntax and differences comparison

Let's take a look at two keywords that have similar functions. Wouldn't you have made two uselessly?

Def description

Let me first give you an example.

def add(x, y):
    return x + y
print(add(3,5))

Here is the result:

8

Functions are written with the def keyword.

add is the name of the function, and the arguments to be passed are defined as x and y.

It has a function that returns the result of adding two values.

If you pass 3 and 5 as arguments to the add function created in this way, you can see that the result is 8.

Lambda description

Let's create the same function as above.

add = lambda x,y: x+y
print(add(2,3))

Here is the result:

5

It uses the keyword lambda to receive x and y as arguments and returns the result of adding the two values.

Lambdas create unnamed functions by default.

And you can write more concisely in one line.

Also, don't use the return keyword.

It can also be used in the same way as a function by assigning it to a variable.

How to use it

Let's look at another usage example to help you understand.

temp = [1,2,3,4,5]
result = list(filter(lambda x:x>2, temp))
print(result)

Here is the result:

[3,4,5]

This is an example of using the filter method to select only values ​​greater than 2 from an array with elements 1 to 5.

lambda receives a value, determines whether it is greater than 2, and returns True or False Boolean values.

The filter method assigns a lambda to the first argument and an array to the second argument.

It traverses the array and produces a result by keeping the value if it is greater than 2 and excluding it otherwise.

The result obtained by filter is created in the form of an array with the list method and stored in the result variable.

Let's create the exact same function with a function.

temp = [1,2,3,4,5]
def comp(x):
    return x > 2
result = list(filter(comp, temp))
print(result)

Here is the result:

[3,4,5]

It doesn't matter how you implement it, but in this example, the lambda is a bit more concise, right?

In fact, if you take a picture of the type, both def and lambda implementations come out the same as functions.

Therefore, you can think of it as a concept that a lambda is included in a function.

In conclusion, it would be better to use the def keyword to create a function that needs to be reused, and to use lambda when you want to create a simple one-time function.

There are 2 replies on this post.

Leave a Reply

Your email address will not be published. Required fields are marked *

en_USEnglish