Skip to main content
Crowdfunding
Python + AI for Geeks
Practice

Creating Concise Anonymous Functions with Lambda

Lambda functions are anonymous functions used to express simple operations without a function name.

The term anonymous means that the function you write doesn’t have a name.

Unlike functions defined with the def keyword, keyword, lambda functions use the lambda keyword, enabling a short and concise expression.

Basic Structure of a Lambda Function
lambda arguments: expression

In this structure, arguments represent inputs to the function, and expression is the operation performed on these inputs.

Here’s a simple example of a lambda function:

Example of a Lambda Function
# Lambda function that returns the sum of two numbers
add = lambda x, y: x + y
# 'add' is a variable pointing to the lambda function

print(add(3, 5)) # Output: 8

# Lambda function that returns the square of a given number
square = lambda x: x * x

print(square(4))
# Output: 16

Beyond simple arithmetic operations like those above, you can create more complex lambda functions using conditions.

Lambda Function with a Conditional Statement
# Lambda function to check if a given number is even or odd
is_even = lambda x: 'Even' if x % 2 == 0 else 'Odd'

print(is_even(3))
# Output: Odd

In the code above, the is_even lambda function uses the condition 'Even' if x % 2 == 0 to return 'Even' if the given number x is divisible by 0, and 'Odd' otherwise.


When to Use Lambda Functions?

Lambda functions have the following advantages over regular functions defined with the def keyword:

  • Concise Function Definition: You can define simple functions in one line, keeping the code clean and easy to read.

  • Use as Function Arguments: They're ideal for passing as arguments to other functions, enhancing code flexibility and reusability.

Example of Passing a Lambda Function as an Argument
# Example of using lambda with the filter() function
numbers = [1, 2, 3, 4, 5]
# Create a new list by filtering even numbers from the list 'numbers'
even_numbers = filter(lambda x: x % 2 == 0, numbers)

print(list(even_numbers))
# Output: [2, 4]

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.