This is a part of my Python Advanced Series. If you want to be an expert in python, check these topics. They are free!

<Link to Advanced Python Topics>

Lambda Functions

Consider a simple function which returns the remainder of two numbers entered by a user. How could we represent this in code?

#Typical way of representing a function
def remainder(a,b):
    return a % b
print(remainder(10,5))
# -> 0

This obviously works but let’s try using a lambda expression.

 

#Using a Lambda Expression
rem = lambda a, b : a%b
print(rem(10,4))
# -> 2

This look way more shorter and expressive right?

Apart from looking easier and more concise, using lambda expressions instead of regular functions makes more sense and can be more logical in some cases. Let’s take another example where we can leverage the power of lambda functions.

#Example of lambda Expression
def power(n):
    return lambda x: x**n

square = power(2)
cubic = power(3)
quadruple = power(4)

print(square(10)) # -> 100
print(cubic(10)) # -> 1000
print(quadruple(10)) # -> 10000
# -> code source: Uzay Macar : Stackoverflow

“When the power() function is called, it returns a lambda function that takes an argument x and returns x to the power of the original value n passed to power().

While lambda functions can be useful for shortening code and reducing the need for named functions, overuse can lead to code that is difficult to read and maintain. It is important to use lambda functions judiciously in appropriate situations. In addition to being returned from functions, lambda functions can also be used as shorthand expressions in other areas of Python such as map() and filter().”

We will be learning map() and filter() functions in another lesson.

If you enjoyed this topic, and want to learn more advanced topics in python then I have a whole series about “Advanced Concepts in Python” you can check that series if you want to increase your knowledge in python.

Leave a Reply

Your email address will not be published. Required fields are marked *