- Aliases
- and operator
- Booleans
- Classes
- Code blocks
- Comments
- Conditional statements
- Console
- Data structures
- datetime module
- Decorator
- Dictionaries
- Docstrings
- enum
- enumerate() function
- Equality operator
- Exception handling
- False
- File handling
- Floats
- For loops
- Formatted strings
- Functions
- Generator
- Greater than operator
- Greater than or equal to operator
- If statement
- in operator
- Indices
- Inequality operator
- Integers
- Iterator
- Lambda function
- Less than operator
- Less than or equal to operator
- List append() method
- List comprehension
- List insert() method
- List pop() method
- List sort() method
- Lists
- Logging
- map() function
- Match statement
- Math module
- Modules
- Multiprocessing
- Multithreading
- None
- not operator
- OOP
- or operator
- Parameters
- print() function
- Random module
- range() function
- Recursion
- Regular expressions
- requests Library
- return statement
- round() function
- Sets
- SQLite
- String join() method
- String replace() method
- String split() method
- Strings
- time.sleep() function
- True
- try...except statement
- Tuples
- Variables
- While loops
- Zip function
PYTHON
Python Lambda Function: Syntax, Usage, and Examples
A Python lambda function is a small, anonymous function that you can define in a single line. It is useful when you need a short function for a quick operation without defining it using def
.
How to Use a Lambda Function in Python
The syntax of a lambda function in Python follows this structure:
lambda arguments: expression
lambda
: The keyword for defining a lambda function.arguments
: One or more inputs, just like a regular function.expression
: The operation that gets evaluated and returned.
Example: Creating a Simple Lambda Function
square = lambda x: x * x
print(square(5)) # Output: 25
This lambda function takes x
as an argument and returns its square.
When to Use a Lambda Function in Python
Lambda functions are useful when you need:
- Short functions that you don’t need to reuse
- Example: Squaring numbers inside a
map()
function.
- Example: Squaring numbers inside a
- To pass functions as arguments
- Example: Sorting lists with custom rules.
- To simplify code
- Example: Replacing short
def
functions with one-liners.
- Example: Replacing short
Examples of Lambda Functions in Python
Using Lambda with map()
map()
applies a function to each element of an iterable.
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x * x, numbers))
print(squared) # Output: [1, 4, 9, 16, 25]
Using Lambda with filter()
filter()
selects elements that match a condition.
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4, 6]
Using Lambda with sorted()
You can sort lists with custom sorting rules using lambda functions.
words = ["apple", "banana", "cherry", "blueberry"]
sorted_words = sorted(words, key=lambda word: len(word))
print(sorted_words) # Output: ['apple', 'banana', 'cherry', 'blueberry']
Learn More About Lambda Functions in Python
Using If-Else in a Lambda Function
Lambda functions can include conditional expressions.
max_value = lambda a, b: a if a > b else b
print(max_value(10, 20)) # Output: 20
Passing a Lambda Function as an Argument
You can pass a lambda function to another function for flexibility.
def apply_operation(func, value):
return func(value)
result = apply_operation(lambda x: x * 3, 5)
print(result) # Output: 15
Using Lambda in a Dictionary
You can use lambda functions inside dictionaries to store different operations.
operations = {
"square": lambda x: x * x,
"double": lambda x: x * 2,
"negate": lambda x: -x
}
print(operations20
Using Lambda with List Comprehension
You can combine lambda functions with list comprehensions for quick transformations.
numbers = [1, 2, 3, 4]
doubled = [(lambda x: x * 2)(n) for n in numbers]
print(doubled) # Output: [2, 4, 6, 8]
Sorting with Lambda and Multiple Criteria
When sorting dictionaries or tuples, lambda functions help specify multiple sorting criteria.
students = [("Alice", 90), ("Bob", 85), ("Charlie", 85)]
sorted_students = sorted(students, key=lambda student: (-student[1], student[0]))
print(sorted_students) # Output: [('Alice', 90), ('Bob', 85), ('Charlie', 85)]
Using Multiline Lambda Functions
By default, lambda functions in Python are limited to a single expression. However, you can work around this by using tuples or other techniques.
multistep = lambda x: (x * 2, x + 3, x ** 2)
print(multistep(5)) # Output: (10, 8, 25)
Assigning a Function Name to a Lambda Function
Unlike normal functions defined with the def
keyword, a lambda function doesn't require an explicit function name. However, you can assign a lambda function to a variable.
multiply = lambda x, y: x * y # Assigning a function name
print(multiply(3, 4)) # Output: 12
- Unlike a normal function, this lambda function is assigned to
multiply
. - The lambda keyword makes function definitions more concise.
Data Science Use Cases
In data science, lambda functions are widely used for quick data transformations.
import pandas as pd
data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]}
df = pd.DataFrame(data)
df['Age Group'] = df['Age'].apply(lambda x: 'Young' if x < 30 else 'Adult')
print(df)
Use cases in data science include data filtering, transformations, and feature engineering.
Combining Lambda with For Loops
Although lambda functions don’t contain loops internally, they can be used inside a for loop.
numbers = [1, 2, 3, 4]
for num in numbers:
print((lambda x: x * 2)(num)) # Applying lambda inside a for loop
For loops allow applying a lambda function to multiple values sequentially.
Using Lambda in Functional Programming
Python supports functional programming, where functions can be passed as arguments or returned from other functions. Higher-order functions like map()
, filter()
, and reduce()
make lambda functions a perfect fit.
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, numbers)) # Functional programming
print(squared) # Output: [1, 4, 9, 16]
- The
map()
function applies the function object created bylambda
to each element. - Higher-order functions like
map()
take another function as an argument.
Lambda Function vs. Regular Function
Regular functions are better when the function logic is complex, while lambda functions are ideal for simple operations.
Using a regular function:
def multiply(x, y):
return x * y
print(multiply(3, 4)) # Output: 12
Using a lambda function:
multiply = lambda x, y: x * y
print(multiply(3, 4)) # Output: 12
Both functions do the same thing, but the lambda version is more compact.
Using Lambda to Pass a Function to a Decorator
Lambda functions can work with decorators when you need quick inline logic.
def decorator(func):
return lambda x: func(x) + 1
@decorator
def square(x):
return x * x
print(square(4)) # Output: 17 (4*4 + 1)
Formatting Strings with Lambda Functions
You can format strings using lambda functions for dynamic output.
format_string = lambda name, age: f"My name is {name} and I am {age} years old."
print(format_string("Alice", 30))
# Output: My name is Alice and I am 30 years old.
Best Practices for Lambda Functions
- Use lambda functions for simple, one-time operations.
- Prefer regular functions when logic requires multiple statements.
- Use lambda functions inside map, filter, sorted, and other built-in functions.
- Avoid writing long, complex lambda expressions that reduce readability.
Python lambda functions offer a quick way to define short, throwaway functions without writing a full function definition. Lambda functions make your code more concise, whether you're filtering data, transforming values, or passing functions as arguments.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.