Skip to main content

Command Palette

Search for a command to run...

How to use Lambda Function in Python? An impressive method in Python

Published
1 min read
How to use Lambda Function in Python? An impressive method in Python
M

I am an AI Developer with a Bachelor's in Software Engineering from City University Peshawar. My expertise lies in Python backend development, machine learning, and AI-driven applications. I am passionate about creating intelligent, data-driven solutions that solve real-world problems. I believe in continuous learning and am always eager to explore new technologies to integrate into my projects. I aim to combine technical excellence with creative problem-solving to deliver impactful and innovative AI solutions.

My career began by working with local companies, and now I focus on building innovative AI-driven products and machine learning models that have the potential to impact people around the globe positively. I have worked on sentiment analysis, real-time currency classification, and weather forecasting using radar images. This website showcases my work and serves as a reflection of my Python, AI, and backend development expertise. I am always committed to delivering high-quality, efficient solutions that solve real problems.

In this blog, I am going to cover the lambda function. It is a function that creates a function object using the lambda keyword. The function object lasts only as long as it's called and then disappears. It can be called by using the keyword 'lambda' following with parameters in the function and then the function body.
The syntax is

lambda arguments: expression

It can take any number of arguments, but can only have one expression. Lambda Function Example Below is a simple lambda function example.

x = lambda a, b: a + b
print(x(5,6))
Output:
11

Uses of Lambda Functions

Lambda function is better shown when they are used as an anonymous function inside another function. Let's suppose you have a function definition that takes one argument, and that argument will be powered by an unknown number:

def power(n):
     return lambda a: a ** n

Use that function definition to make a function that always squares the number you send

square = power(2)
print(square(3))

Or similarly, we can generate tons of other functions from that single function such as

cube = power(3)
print(cube(3))
IVTimes = power(4)
print(IVTimes(3))