Python Lambda function

Introduction Reading Time: 10 min

Table of Contents

Description

A lambda function in Python is a small anonymous function defined using the lambda keyword. It can take any number of arguments, but can only have one expression. It's commonly used for short, throwaway functions especially in functional programming scenarios like map(), filter(), and sorted().

Prerequisites

  • Knowledge of basic functions
  • Familiarity with expressions
  • Understanding of higher-order functions like map(), filter(), etc.

Examples

Here's a simple program in Python:

✅ Basic Lambda Function
# A simple lambda function that adds 10 to a number
add_ten = lambda x: x + 10

print(add_ten(5))  # Output: 15
✅ Lambda with Multiple Arguments
# Lambda to multiply two numbers
multiply = lambda a, b: a * b

print(multiply(4, 5))  # Output: 20
✅ Using Lambda with map()
# Doubles each number in the list
nums = [1, 2, 3, 4]
doubled = list(map(lambda x: x * 2, nums))
print(doubled)  # Output: [2, 4, 6, 8]
✅ Using Lambda with filter()
# Filters even numbers from the list
even_nums = list(filter(lambda x: x % 2 == 0, nums))
print(even_nums)  # Output: [2, 4]
✅ Lambda in sorted() with key
# Sorts a list of tuples based on the second element
pairs = [(1, 4), (2, 1), (3, 9)]
sorted_pairs = sorted(pairs, key=lambda x: x[1])
print(sorted_pairs)  # Output: [(2, 1), (1, 4), (3, 9)]

      

Real-World Applications

Used in data transformation pipelines

Simplifies callback functions in GUI or web development

Helps sort or filter complex datasets on the fly

Widely used in pandas and NumPy for inline operations

Common in AI/ML pipelines for inline feature transformations

Where topic Can Be Applied

Data Science: Inline transformations in pandas, NumPy

Web Development: Inline route functions or conditions

Automation Scripts: Quick filtering/mapping without extra function definitions

Machine Learning: Lambda used in data preprocessing

Functional Programming: Combined with map(), reduce(), etc.

Resources

Topic video source

A comprehensive video

Watch

Python pdf

pdf on topic

Visit

Interview Questions

What is a lambda function in Python?

How is a lambda function different from a normal function?

Can lambda functions have multiple expressions?

Where would you use a lambda over a def function?

How can you use lambda with map(), filter(), or sorted()?