Lambda Function
Lambda Function
An anonymous function. Python lambda, JS arrow function. Concise function definition.
Lambda Function
An anonymous function. Python lambda, JS arrow function. Concise function definition.
A lambda function is an anonymous function that is defined without a name and is used for one-off or simple operations. Unlike traditional function definitions, a lambda function is written as a single line or a concise expression, which improves code readability and productivity. In Python, lambda functions are expressed with the lambda keyword, and in JavaScript, with arrow functions (=>).
The concept of the lambda function originates from lambda calculus, developed in the 1930s by the mathematician Alonzo Church. Lambda calculus is a formal system for studying computability, and it expresses the definition and application of functions mathematically. This concept was introduced into programming languages starting with LISP in the 1950s–60s, and today most modern languages support lambda functions.
The core principles of the lambda function are three. First, anonymity: a function does not need to be given a name. Second, as a first-class citizen, it can be assigned to a variable or passed as an argument to another function. Third, with the closure property, it can capture and use variables from the outer scope at the point where it was defined.
In practice, lambda functions are widely used for data transformation together with higher-order functions such as map(), filter(), and reduce(). They make code concise in any situation that requires a one-off function, such as event handlers, callback functions, and sort key definitions. In addition, serverless computing platforms such as AWS Lambda extend the concept of the lambda function, providing a cloud service that lets you run code without managing servers.
# Python 람다 함수 예제
# 기본 람다 함수 정의
square = lambda x: x ** 2
print(square(5)) # 출력: 25
# 여러 인자를 받는 람다 함수
add = lambda a, b: a + b
print(add(3, 7)) # 출력: 10
# map()과 함께 사용
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # 출력: [1, 4, 9, 16, 25]
# filter()로 짝수만 추출
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # 출력: [2, 4]
# 정렬 기준으로 사용
users = [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}]
sorted_users = sorted(users, key=lambda u: u['age'])
print(sorted_users) # Bob이 먼저 (나이순 정렬)
// JavaScript 화살표 함수 (람다 함수)
// 기본 화살표 함수
const square = (x) => x ** 2;
console.log(square(5)); // 출력: 25
// 여러 인자를 받는 화살표 함수
const add = (a, b) => a + b;
console.log(add(3, 7)); // 출력: 10
// map()과 함께 사용
const numbers = [1, 2, 3, 4, 5];
const squared = numbers.map(x => x ** 2);
console.log(squared); // 출력: [1, 4, 9, 16, 25]
// filter()로 짝수만 추출
const evens = numbers.filter(x => x % 2 === 0);
console.log(evens); // 출력: [2, 4]
// 이벤트 핸들러로 사용
document.querySelector('#btn').addEventListener('click', (e) => {
console.log('버튼이 클릭됨!', e.target);
});
// Promise 체인에서 활용
fetch('/api/users')
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
// Java 람다 표현식 (Java 8+)
import java.util.*;
import java.util.stream.*;
public class LambdaExample {
public static void main(String[] args) {
// 기본 람다 표현식 (Runnable)
Runnable task = () -> System.out.println("Hello Lambda!");
task.run();
// Comparator 람다로 정렬
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.sort((a, b) -> a.compareTo(b));
// Stream API와 함께 사용
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// map: 제곱 계산
List<Integer> squared = numbers.stream()
.map(x -> x * x)
.collect(Collectors.toList());
System.out.println(squared); // [1, 4, 9, 16, 25]
// filter: 짝수만 추출
List<Integer> evens = numbers.stream()
.filter(x -> x % 2 == 0)
.collect(Collectors.toList());
System.out.println(evens); // [2, 4]
// forEach로 출력
numbers.forEach(n -> System.out.println(n));
}
}
"Rather than creating a separate function for this API call, I think handling it inline with a lambda function would make the code much more concise. We can express the data transformation logic cleanly with a map and filter chain."
"There are three key differences between lambda functions and regular functions. First, a lambda is anonymous, so it suits one-off logic rather than reuse. Second, a lambda is expression-based, so it is more effective for simple transformations than for complex logic. Third, thanks to the closure property, it can capture variables from the outer scope, which makes it powerful when used with higher-order functions. In Python, only a single expression is allowed, and it is also important that the `this` binding of JavaScript arrow functions differs from that of regular functions."
"Now that this lambda function is 3 lines or more, it has actually become harder to read. I think lambdas should be used only for simple logic that ends in a single line, and in complex cases like this, it would be better to separate it into an explicit function to make the intent clear."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
If you put complex logic such as conditionals, loops, and exception handling into a lambda function, readability drops sharply. Use lambdas only for simple transformations or filtering, and define complex logic as an explicit function.
Because a lambda function has no name, it appears only as '<lambda>' in stack traces. Since error tracing becomes difficult, use named functions, which are easier to debug and test, for important business logic.
Nesting lambdas in multiple layers or excessively chaining map-filter-reduce makes the code hard to understand. Use intermediate variables where appropriate, or split the logic into steps to preserve readability.
Use lambda functions for logic that is one-off and can be expressed in a single line, such as sort keys, simple callbacks, and simple data transformations. A good rule of thumb is "if a lambda takes more than 3 seconds to read, split it out into a function."