Lambda Function in Python

 

What is a Lambda Function? 

A lambda function in Python is a small, anonymous function that can have any number of arguments but only one expression. Think of it as a ninja function —silent, quick, and efficient!

Why Use Lambda Functions?

  • Saves space – No need for full def functions 
  • Used for short operations – Great for quick calculations 
  • Works well inside other functions – Ideal for functional programming 

Basic Lambda Syntax 

A lambda function is written using the lambda keyword:

lambda arguments: expression

Example:

add = lambda a, b: a + b
print(add(5, 3))  # Outputs: 8

Same as:

def add(a, b):
    return a + b

Using Lambda Inside Functions 

Lambdas are often used inside other functions:

def multiplier(n):
    return lambda x: x * n

double = multiplier(2)
print(double(5))  # Outputs: 10

Lambda with map(), filter(), and sorted() 

Lambdas shine in functions like map() and filter().

numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared)  # Outputs: [1, 4, 9, 16, 25]

Filtering even numbers:

evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)  # Outputs: [2, 4]

Summary 

Concept Description
lambda Creates small anonymous functions
Single Expression Can only contain one expression
Used in map(), filter(), sorted() Great for short tasks

 

Post a Comment

0 Comments