Python’s Weird Lambda Functions: Using Them in Chaotic Ways
Lambda functions are amongst the most distinctive and also most frequently misunderstood features in Python. Originally introduced as “anonymous functions,” the lambda expressions enable us to write small functions in one line, without explicitly defining the name of a function. While most developers are comfortable using a basic form of lambda, its flexibility and brevity often lead to chaotic-and sometimes brilliant-use cases. Weird and wondrous, we dive into the ways in which you could use lambda functions, both the practical and chaotic scenarios.
What is a Lambda Function in Python? In Python, a lambda function is an anonymous small function that can be defined with the keyword lambda. Syntax is simple:
lambda arguments: expressionLambdas are meant to be used when a full function definition using def would be redundant or too wordy. Simple example:
# Standard function
def add(x, y):
return x + y
# Lambda function
add_lambda = lambda x, y: x + y
print(add_lambda(3, 5)) # Output: 8While the above is pretty straight-forward, the real power and sometime undue complexity of lambda functions comes when we begin to push them to their limits.
Higher-order functions are functions that take other functions as arguments or return them as values. Lambda is a natural fit here, since the code is often shorter and arguably cleaner. On the other hand, lambda’s flexibility also lets expressions quickly become convoluted and unreadable. For instance, take a look at
# List of strings
animals = ['elephant', 'dog', 'cat', 'giraffe']
# Sort animals by length (descending) using lambda
sorted_animals = sorted(animals, key=lambda x: len(x), reverse=True)
print(sorted_animals) # Output: ['elephant', 'giraffe', 'dog', 'cat']This is an ok use, but the chaos begins when we start mixing nested lambdas with other higher-order functions such as map, filter, or reduce.
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Square each number, filter for values over 10, and sum them in one line using lambdas
result = sum(filter(lambda x: x > 10, map(lambda x: x ** 2, numbers)))
print(result) # Output: 29 (16 + 9 + 4 from squares over 10)We are mapping every number in one line, filtering the values and summing everything. The more operations you add, the less readable this line is, thus creating effective but messy code to read.
Lambda chains happen when we pass lambda functions as arguments to other lambda functions, or when we nest them deeply. This can be quite hard to track in a hurry, but for enthusiasts of code golf this is oddly satisfying- writing the shortest code possible.
Here’s a crazy example:
# Chained lambdas
operation = lambda x: (lambda y: (lambda z: x + y + z))(5)(10)
print(operation(2)) # Output: 17The above example is a curiously strange construct for simple addition, but it involves three nested lambda expressions, each taking one parameter: the outermost takes x and calls a lambda taking y and so on. It does little, but in a very awkward and circuitous fashion.
Get S M Shahinul Islam’s stories in your inbox
Join Medium for free to get updates from this writer.
Self-executing lambda functions are lambdas that immediately invoke themselves. This is actually not necessary to do in Python very often, but it can be an interesting way to write code in some instances if you want to make things a bit different from the norm.
# Self-executing lambda to add two numbers
print((lambda x, y: x + y)(4, 5)) # Output: 9This is a concise way of executing a lambda immediately, but it gets messier rather quickly once we add a little complexity:
# Self-executing lambda with conditionals
print((lambda x: x * 2 if x > 5 else x + 5)(7)) # Output: 14While these are entertaining to create, they tend to confuse the reader when the lambda involves a number of conditions, arithmetic, or even other lambdas.
Lambdas in Python are usually constrained to one-line of expression and cannot explicitly support recursion as that would require a name by which it could call itself. However, with just a bit of trickery, a recursive lambda can be had with the assistance of an assistant function.
Here’s an example of a recursive lambda for calculating factorials:
# Recursive lambda for factorial using a helper function
factorial = (lambda f: lambda x: 1 if x == 0 else x * f(f)(x - 1) (lambda f: lambda x: 1 if x == 0 else x * f(f)(x - 1))
print(factorial(5)) # Output: 120This is a trick to make recursion work but the resulting lambda is highly hard to read and should be used only if you want your colleagues to bang their head against the wall.
Currying works by taking a function that takes multiple arguments and turning it into a chain of functions each taking a single argument. Lambda functions make currying short, but it can get into a mess of single-argument functions fairly quickly.
# Curried lambda function for addition
add = lambda x: (lambda y: x + y)
add_five = add(5)
print(add_five(3)) # Output: 8Currying does enable us to create partial functions on the fly. But readability drops when overused or in involved expressions.
A quirkier use of lambdas might be as dictionary values where each lambda performs some different operation depending on a key. This can create some very flexible code structures but also can get out of hand if not properly documented.
# Dictionary of lambdas
operations = {
'add': lambda x, y: x + y,
'subtract': lambda x, y: x - y,
'multiply': lambda x, y: x * y,
'divide': lambda x, y: x / y if y != 0 else 'undefined'
}
# Example usage
print(operations['add'](10, 5)) # Output: 15
print(operations['divide'](10, 0)) # Output: 'undefined'This is an easy way to extend the operations without having to define additional functions, but a complex dictionary of lambdas can be hard to maintain, especially as the expressions inside each lambda get more complex.
Python’s lambda functions are powerful and flexible but can be used in unexpected and even chaotic ways. While lambda functions are in their element in situations that call for conciseness, they surely can become a double-edged sword in cases of overusing or using without consideration. Though embracing the quirkiness of lambda may lead to clever solutions, one should not forget about an extremely important aspect like readability and maintainability.
The chaotic charm of lambda functions in Python lies in their wise usage-when and where to use them.
Originally published at https://smshahinulislam.substack.com.







