Python Lambda Functions
Lambda Functions are anonymous functions means that the function is without a name. As we already know def keyword is used to define a normal function in Python. Similarly, lambda keyword is used to define an anonymous function in Python.
Example: In the example, we defined a lambda function (upper) to convert a string to its upper case using upper().
s1 = 'GeeksforGeeks'
s2 = lambda func: func.upper()
print(s2(s1))
Output
GEEKSFORGEEKS
Explanation: s2 is a lambda function that takes a string and returns it in uppercase. Applying it to 'GeeksforGeeks' gives the result.
Syntax
lambda arguments : expression
- lambda: The keyword to define the function.
- arguments: A comma-separated list of input parameters (like in a regular function).
- expression: A single expression that is evaluated and returned.
Use Cases of Lambda Functions
Let's see some of the practical uses of the Python lambda function.
1. Using with Condition Checking
A lambda function can include conditions using if statements.
Example 1: Here, the lambda function uses nested if-else logic to classify numbers as Positive, Negative or Zero.
n = lambda x: "Positive" if x > 0 else "Negative" if x < 0 else "Zero"
print(n(5))
print(n(-3))
print(n(0))
Output
Positive Negative Zero
Explanation:
- The lambda function takes x as input.
- It uses nested if-else statements to return "Positive," "Negative," or "Zero."
Example 2: This lambda checks divisibility by 2 and returns "Even" or "Odd" accordingly.
check = lambda x: "Even" if x % 2 == 0 else "Odd"
print(check(4))
print(check(7))
Output
Even Odd
Explanation:
- The lambda checks if a number is divisible by 2 (x % 2 == 0).
- Returns "Even" for true and "Odd" otherwise.
- This approach is useful for labeling or categorizing values based on simple conditions.
2. Using with List Comprehension
Combining lambda with list comprehensions enables us to apply transformations to data in a concise way.
Example: This code creates a list of lambda functions, each multiplying its input by 10 and then executes them one by one.
li = [lambda arg=x: arg * 10 for x in range(1, 5)]
for i in li:
print(i())
Output
10 20 30 40
Explanation:
- The lambda function multiplies each element by 10.
- The list comprehension iterates through li and applies the lambda to each element.
- This is ideal for applying transformations to datasets in data preprocessing or manipulation tasks.
3. Using for Returning Multiple Results
Lambda functions do not allow multiple statements, however, we can create two lambda functions and then call the other lambda function as a parameter to the first function.
Example: The lambda calculates both sum and product of two numbers and returns them as a tuple.
calc = lambda x, y: (x + y, x * y)
res = calc(3, 4)
print(res)
Output
(7, 12)
Explanation:
- The lambda function performs both addition and multiplication and returns a tuple with both results.
- This is useful for scenarios where multiple calculations need to be performed and returned together.
4. Using with filter()
The filter() function in Python takes in a function and a list as arguments. This offers an elegant way to filter out all the elements of a sequence "sequence", for which the function returns True.
Example: Here, the lambda is used as a filtering condition to keep only even numbers from the list.
n = [1, 2, 3, 4, 5, 6]
even = filter(lambda x: x % 2 == 0, n)
print(list(even))
Output
[2, 4, 6]
Explanation:
- The lambda function checks if a number is even (x % 2 == 0).
- filter() applies this condition to each element in nums.
5. Using with map()
The map() function in Python takes in a function and a list as an argument. The function is called with a lambda function and a new list is returned which contains all the lambda-modified items returned by that function for each item.
Example: This code doubles each element of the list using a lambda function and returns a new list.
a = [1, 2, 3, 4]
b = map(lambda x: x * 2, a)
print(list(b))
Output
[2, 4, 6, 8]
Explanation:
- The lambda function doubles each number.
- map() iterates through a and applies the transformation.
6. Using with reduce()
The reduce() function in Python takes in a function and a list as an argument. The function is called with a lambda function and an iterable and a new reduced result is returned. This performs a repetitive operation over the pairs of the iterable. The reduce() function belongs to the functools module.
Example: Here, the lambda multiplies two numbers at a time and reduce() applies this across the whole list to calculate the product.
from functools import reduce
a = [1, 2, 3, 4]
b = reduce(lambda x, y: x * y, a)
print(b)
Output
24
Explanation:
- The lambda multiplies two numbers at a time.
- reduce() applies this operation across the list.
Difference Between lambda and def Keyword
In Python, both lambda and def can be used to define functions, but they serve slightly different purposes. While def is used for creating standard reusable functions, lambda is mainly used for short, anonymous functions that are needed only temporarily.
Letâs see an example to understand this better:
# Using lambda
sq = lambda x: x ** 2
print(sq(3))
# Using def
def sqdef(x):
return x ** 2
print(sqdef(3))
Output
9 9
Explanation:
- lambda function sq takes a number and returns its square.
- regular function sqdef does the same but is defined using the def keyword.
- Both approaches give the same result, but lambda is more concise.
Now, letâs see a comparison between these two in tabular form:
Feature | lambda Function | Regular Function (def) |
---|---|---|
Definition | Single expression with lambda. | Multiple lines of code. |
Name | Anonymous (or named if assigned). | Must have a name. |
Statements | Single expression only. | Can include multiple statements. |
Documentation | Cannot have a docstring. | Can include docstrings. |
Reusability | Best for short, temporary functions. | Better for reusable and complex logic. |