In Python, besides defining functions using the def keyword, there is a way to create “nameless functions (anonymous functions)” using lambda expressions.
Using lambda expressions allows you to write very short functions in a single line on the spot, without the hassle of defining them formally. This is particularly useful when passing processing logic as arguments to other functions (higher-order functions).
This article explains the basic syntax of lambda expressions and practical usage examples combined with map() and sorted().
Basic Syntax of lambda Expressions
lambda expressions are written with the following syntax:
Syntax:
lambda arguments: expression_to_return
Let’s compare this with a function definition using def. As an example, consider a function that squares a received number and returns it.
Normal Function Definition (def)
def square_def(x):
return x ** 2
print(f"def: {square_def(5)}")
Definition with lambda Expression
# Create a function that takes x and returns x ** 2, assigning it to variable square_lambda
square_lambda = lambda x: x ** 2
print(f"lambda: {square_lambda(5)}")
Output:
def: 25
lambda: 25
There is no need to write a return statement; the result of the expression automatically becomes the return value. As shown, for simple calculations or processing, using lambda allows for very concise code.
Using with Higher-Order Functions
The true value of lambda expressions is demonstrated when used with “Higher-Order Functions” that accept functions as arguments. It is suitable for passing “disposable processing” logic where creating a named function with def would be overkill.
1. Using with map()
map() is a built-in function that applies a specified function to all elements of a list (or other iterables). Here is an example of converting a list of numbers into “Currency (String)” format.
price_list = [1000, 2500, 500, 12000]
# Apply the format f"{x:,} yen" to each element x in the list
# Convert the map object to a list with list() and display
formatted_prices = list(map(lambda x: f"{x:,} yen", price_list))
print(formatted_prices)
Output:
['1,000 yen', '2,500 yen', '500 yen', '12,000 yen']
2. Using with filter()
filter() is a function that extracts only elements that match a condition (where the result is True). Here is an example of extracting only “multiples of 3” from a list of numbers.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Extract only elements where x % 3 == 0 (divisible by 3)
multiples_of_three = list(filter(lambda x: x % 3 == 0, numbers))
print(multiples_of_three)
Output:
[3, 6, 9]
3. Using with sorted() (Specifying Sort Key)
The most practical use is specifying a key for sorting lists. lambda is very useful when you want to sort a list of dictionaries or tuples based on a specific element. Here is an example of sorting a list of user information dictionaries by “age”.
# List of user information
user_list = [
{"name": "Tanaka", "age": 45},
{"name": "Sato", "age": 30},
{"name": "Suzuki", "age": 38}
]
# Sort based on age
# lambda x: x["age"] is a function that receives a dictionary and returns the age
sorted_users = sorted(user_list, key=lambda x: x["age"])
print(sorted_users)
Output:
[{'name': 'Sato', 'age': 30}, {'name': 'Suzuki', 'age': 38}, {'name': 'Tanaka', 'age': 45}]
By passing a lambda expression to the key= argument, we concisely instructed Python to “compare and sort based on the age value inside the dictionary, not the dictionary itself.”
Summary
- You can create anonymous functions in the format
lambda arguments: expression. - Do not write
return; the evaluation result of the expression becomes the return value. - Combining with higher-order functions like
map(),filter(), andsorted()allows for concise and efficient code. - If the processing becomes complex and requires multiple lines, it is recommended to define a normal function with
definstead of forcing alambda.
