Python Reserved Keywords in Python Built in functions
Python Lambda Functions
Python lambda expression are small, anonymous utility created using the lambda reserved keyword of Python. These statements are typically one-liners designed for simple operations, often used as arguments in higher-order functions like map() , filter() , or sorted() . Lambda functions are also known as “inline operation” because they’re usually written where they’re used, without formally defining a function with def .
Syntax
The basic syntax of a lambda Expression:
lambda arguments : expression
- arguments : The inputs to the lambda Expression, which can be one or more parameters separated by commas.
- expression : A single expression that the lambda statement returns.
Tip: For reusable and complex logic, use a
function ; for short, one-time operations, use a lambda.
Example 1: Basic Lambda Expression
Here’s a simple example of a lambda statement that adds two numbers.
add = lambda x , y : x + y
print (add (3 , 5 ))
Output:
8
Example 2: Lambda statement with map()
Lambda statements are often used with map() to apply an operation to each item in an iterable, such as a list.
numbers = [1 , 2 , 3 , 4 ]
squared = list (map (lambda x : x ** 2 , numbers ))
print (squared )
Output:
[1, 4, 9, 16]
Example 3: Using Lambda with filter()
Lambda statements are commonly paired with filter() to select items from an iterable based on 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]
Example 4: Sorting with Lambda in sorted()
You can use lambda statement as a key argument in sorted() to sort complex data structures like lists of tuples or dictionaries.
pairs = [(1 , 'apple' ), (2 , 'orange' ), (3 , 'banana' )]
sorted_pairs = sorted (pairs , key =lambda x : x [1 ])
print (sorted_pairs )
Output:
[(1, 'apple'), (3, 'banana'), (2, 'orange')]
Example 5: Lambda with Default Arguments
Lambda statement can also include default parameters, which allows for flexible functionality without defining multiple functions.
multiply = lambda x , y =2 : x * y
print (multiply (3 )) # Uses default y=2
print (multiply (3 , 4 )) # Uses provided y=4
Output:
6
12
Python Lambda expression: Advanced Examples
Example 6: Lambda for Conditional Expressions
Lambda statement can handle conditional expressions to return values based on conditions.
is_even = lambda x : "Even" if x % 2 == 0 else "Odd"
print (is_even (4 )) # Output: Even
print (is_even (5 )) # Output: Odd
Example 7: Using Lambda with reduce() for Accumulation
Lambda Expression work well with reduce() from the `functools` module to apply an operation to an iterable and reduce it to a single result.
from functools import reduce
numbers = [1 , 2 , 3 , 4 ]
sum_all = reduce (lambda x , y : x + y , numbers )
print (sum_all ) # Output: 10
Example 8: Lambda for Sorting a List of Dictionaries
Lambda statement are useful for creating custom sort keys, as seen in sorting lists of dictionaries.
students = [
{"name" : "Alice" , "grade" : 85 },
{"name" : "Bob" , "grade" : 90 },
{"name" : "Charlie" , "grade" : 80 }
]
sorted_students = sorted (students , key =lambda student : student ["grade" ])
print (sorted_students )
Output ( sorted based on grade )
[
{'name': 'Charlie', 'grade': 80},
{'name': 'Alice', 'grade': 85},
{'name': 'Bob', 'grade': 90}
]
Example 9: Lambda to Find Max/Min in Nested Lists
Use lambda statement with max() and min() to identify values based on a custom criterion.
points = [(2 , 5 ), (3 , 1 ), (4 , 7 ), (1 , 9 )]
highest_y = max (points , key =lambda point : point [1 ])
print (highest_y ) # Output: (1, 9)
Example 10: Lambda with any() and all()
You can combine lambda with any() and all() to apply conditions across iterables.
numbers = [1 , 2 , 3 , 4 ]
print (any (map (lambda x : x % 2 == 0 , numbers ))) # Output: True (because 2 and 4 are even)
print (all (map (lambda x : x > 0 , numbers ))) # Output: True (all numbers are positive)
Example 11: Lambda with Nested Lambda Utility
Lambda operation can even be nested, though this may reduce readability.
multiply = lambda x : lambda y : x * y
double = multiply (2 )
print (double (5 )) # Output: 10
Example 12: Lambda in Dictionaries
Lambda Syntax can be stored in dictionaries for quick command or mappings.
operations = {
"add" : lambda x , y : x + y ,
"subtract" : lambda x , y : x - y ,
"multiply" : lambda x , y : x * y
}
print (operations ["add" ](5 , 3 )) # Output: 8
print (operations ["multiply" ](5 , 3 )) # Output: 15
Use Cases for Lambda keyword
Quick One-Liner syntax : Ideal for small operations where defining a function would be overkill.
Higher-Order operations : Lambda statement work well with functions like map() , filter() , and reduce() for functional programming tasks.
Sorting and Grouping Data : Use in sorted() or groupby() for custom sorting or grouping without needing separate helper functions.
Lambda keyword provide flexibility and conciseness in Python programming. While powerful, they are best used for simple, short tasks since their anonymous nature can reduce readability for more complex operations.
« All Reserved keywords in Python
« All Built in Functions in Python slice()
← Subscribe to our YouTube Channel here