Python Logo

Lambda


What are Python lambda functions?

Python lambda functions are anonymous functions that can be defined and used in a single expression. Lambda functions are typically used for simple, one-off tasks, such as sorting a list or converting a string to uppercase.

How to define a Python lambda function

The syntax for defining a Python lambda function is as follows:

 

Python

lambda arguments: expression
 

The arguments are the input parameters that the lambda function takes. The expression is the code that the lambda function executes.

Example:

 

Python

# Define a lambda function that adds two numbers
add_two_numbers = lambda a, b: a + b

# Call the lambda function
result = add_two_numbers(1, 2)

# Print the result
print(result)
 

Output:

 

3
 

How to use Python lambda functions

Lambda functions can be used anywhere in your code where a regular function can be used. Lambda functions are often used in conjunction with built-in functions, such as map(), filter(), and reduce().

Example:

 

Python

# Use a lambda function to sort a list of numbers
my_list = [5, 3, 2, 1, 4]
sorted_list = sorted(my_list, key=lambda x: x)

# Print the sorted list
print(sorted_list)
 

Output:

 

[1, 2, 3, 4, 5]
 

Benefits of using Python lambda functions

There are several benefits to using Python lambda functions:

  • Conciseness: Lambda functions can be very concise, which can make your code more readable and maintainable.
  • Flexibility: Lambda functions can be used in a variety of ways, including in conjunction with built-in functions and with other lambda functions.
  • Power: Lambda functions can be used to perform complex tasks, such as sorting and filtering data.

Conclusion

Python lambda functions are a powerful tool that can help you to write more concise, flexible, and powerful code. By understanding how to use Python lambda functions, you can become a better Python programmer.