본문 바로가기
Study Note/Python

Lambda function

by jhleeatl 2024. 4. 5.

A lambda function, also known as an anonymous function or a lambda expression, is a concise way to define a small, one-line function in Python.

 

Unlike normal functions, lambda functions are defined without a name and can have any number of parameters, but can only contain a single expression. 

The syntax for a lambda function is:

lambda parameters: expression



Here, parameters are the input values to the function, and expression is the operation performed on the parameters to produce a result. Lambda functions are commonly used when you need a simple function for a short period of time add don't want to define a formal function using the `def` keyword.

For example, a lambda function to add two numbers together would look like this:

add = lambda x, y: x + y

 



This creates a lambda function that takes two parameters `x` and `y`, and returns their sum. You can then use this fucction like any other function:

 

result = add(3, 5)

 


The result would be `8`, as `3 + 5 = 8`. Lambda functions are often used with higher-order functions like `map()`, `filter()`, and `reduce()`, as well as in situations where a function is expected as an argument, such as in sorting or event handling.

 

numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled)  # result : [2, 4, 6, 8, 10]

'Study Note > Python' 카테고리의 다른 글

Taitanic data analysis  (0) 2024.04.30
Python Data Types  (0) 2024.04.25
10. Purpose of 'while' and 'for in'  (0) 2024.04.02
9. Method vs Function / Dictionary vs List  (0) 2024.03.28
8. Function simplification  (0) 2024.03.27