In Python, a lambda function is an anonymous function meaning it is defined without a name. Unlike regular functions defined using def keyword, lambda functions are created using lambda keyword
They are useful for writing small, simple functions in a concise way, especially when you need a function temporarily.
Syntax
lambda arguments : expression
- arguments: Input parameters (can be zero or more).
- expression: A single expression evaluated and returned by the function.
Basic Example
Here’s a simple lambda function that checks if a number is even or odd:
Python
calc = lambda num: "Even number" if num % 2 == 0 else "Odd number"
print(calc(20))
Explanation: calc creates an anonymous function that checks if a number is divisible by 2. If yes, returns "Even number", otherwise "Odd number".
Key Properties of Lambda Functions
- Lambda functions can have any number of arguments but only one expression.
- The expression is evaluated and returned automatically no explicit return needed.
- Lambda functions are syntactically restricted to a single expression (no multiple statements or commands).
- They are often used where small, one-off function objects are required for example, as arguments to other functions.
Examples of Lambda Function
Example 1: Lambda Returns a Function Object
This code prints the lambda function object itself instead of executing it.
Python
string = 'GeeksforGeeks'
print(lambda string: string) # Lambda here returns a function object, not a value
Output<function <lambda> at 0x7f42b0b7f100>
Explanation:
- lambda string: string - Defines an anonymous function that takes one argument (string) and returns it unchanged.
- print(lambda string: string) - Prints the function object itself, not its output, because lambda is not called here.
- Output <function <lambda> at 0x7fd7517ade18> is Python’s way of showing memory address where the function is stored.
If you actually want to see "GeeksforGeeks", you’d need to call the lambda:
print((lambda string: string)(string))
Example 2: Lambda vs Normal Functions
This code compares a normal function (defined with def) and a lambda function, both used to find cube of a number.
Python
def cube(y):
print("Finding cube of number:",y)
return y * y * y
lambda_cube = lambda num: num ** 3
# Calling normal function
print("Invoking function defined with def keyword:")
print(cube(30))
# Calling lambda function
print("Invoking lambda function:")
print(lambda_cube(30))
OutputInvoking function defined with def keyword:
Finding cube of number: 30
27000
Invoking lambda function:
27000
Explanation:
- def cube(y) - Defines a normal function named cube that takes y as input.
- return y * y * y - Returns cube of y using multiplication.
- lambda num: num ** 3 - Creates a lambda function that calculates cube of num using exponentiation.
Note: Lambda functions cannot contain multiple statements (like print). Using def is better for complex operations.
Example 3: Using Lambda with filter() to Remove Even Numbers
In this Example, lambda function is used with filter() to extract only odd numbers from a list.
Python
my_list = [1, 2, 3, 4, 5]
new_list = list(filter(lambda x: x % 2 != 0, my_list))
print(new_list)
Explanation: filter(lambda x: x % 2 != 0, my_list) keeps numbers where number is not divisible by 2(odd numbers).
This example shows three lambda functions that perform text and number operations removing digits from a string, adding an exclamation mark and summing digits of a number.
Python
filter_nums = lambda s: ''.join([ch for ch in s if not ch.isdigit()])
print("filter_nums():", filter_nums("Geeks101"))
do_exclaim = lambda s: s + '!'
print("do_exclaim():", do_exclaim("I am tired"))
find_sum = lambda n: sum([int(x) for x in str(n)])
print("find_sum():", find_sum(101))
Outputfilter_nums(): Geeks
do_exclaim(): I am tired!
find_sum(): 2
Explanation:
- lambda s: ''.join([ch for ch in s if not ch.isdigit()]) - Creates a lambda that removes all digits from a given string.
- lambda s: s + '!' - Creates a lambda that adds an exclamation mark to a string.
- lambda n: sum([int(x) for x in str(n)]) - Creates a lambda that converts a number to a string, splits into digits, converts back to integers and sums them.
Example 5: Lambda Inside Common Python Functions
Here, lambda function is used with sorted(), filter() and map() to perform numerical sorting, filtering and transformation on a list of string numbers.
Python
l = ["1", "2", "9", "0", "-1", "-2"]
# Sort numerically using custom key
print("Sorted numerically:", sorted(l, key=lambda x: int(x)))
# Filter positive even numbers
print("Filtered positive even numbers:", list(filter(lambda x: not (int(x) % 2 == 0 and int(x) > 0), l)))
# Add 10 to each item and convert back to string
print("Operation on each item using map():", list(map(lambda x: str(int(x) + 10), l)))
OutputSorted numerically: ['-2', '-1', '0', '1', '2', '9']
Filtered positive even numbers: ['1', '9', '0', '-1', '-2']
Operation on each item using map(): ['11', '12', '19', '10', '9', '8']
Explanation:
- sorted(l, key=lambda x: int(x)) - Sorts list numerically by converting each string to an integer.
- filter(lambda x: not (int(x) % 2 == 0 and int(x) > 0), l) - Filters out positive even numbers from list.
- map(lambda x: str(int(x) + 10), l) - Adds 10 to each number (after converting to integer) and converts it back to a string.
When to Avoid Lambda Functions?
- When the function is complex or requires multiple statements.
- When you need better readability or debugging (named functions help).
- When you want to add documentation (docstrings) or annotations.
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice