Login Register
×

What are Lambda Functions in Python?

What are Lambda Functions in Python?

A lambda function looks like a small topic, but it has a big impact on Python programming. It does not have a name; for this reason, it’s called an anonymous function.

A lambda function is a tiny, one-line function that you can create without using the def keyword. We will use a lambda function when:

  • We want to perform a quick calculation
  • We don’t want to write a full function using def
  • The logic is very small and is used only once
  • We want clean, short, efficient code

This function can take any number of inputs, but it contains only one expression (no long code blocks).

Syntax of a Lambda Function

The syntax of a lambda function is simple:

lambda arguments: expression
  • lambda: This keyword tells Python that you are creating a short, temporary function.
  • arguments: These are the input values the lambda function will receive. A lambda can have zero, one, or multiple arguments.
  • expression: This is the single calculation or operation that the lambda performs.

Example1 : Calculating Remaining Seats in a Classroom

# Lambda to calculate how many seats are left
remaining_seats = lambda total, occupied: total - occupied

print(remaining_seats(40, 28))

# Example output: 12

In this example:

  • total refers to several available seats.
  • occupied means the number of students already seated.
  • The lambda returns the leftover seats in one line.

Differences Between Lambda Functions and Regular Functions

FeatureLambda FunctionsRegular Functions
DefinitionSingle expressionMultiple statements allowed
NameAnonymous (no name)Requires a name
ComplexityBest for simple operationsSuitable for complex logic
Use CasesOne-time, quick tasksRepeated, reusable tasks

Examples of Lambda Functions

1. Lambda Function Without Arguments

A lambda function can exist even without taking any input and returns a constant value.

# Lambda function that returns a fixed motivational line
motivate = lambda: "Keep learning, you're getting better!"

print(motivate())

# Output: Keep learning, you're getting better!

2. Lambda Function with Multiple Arguments

Lambda can accept multiple inputs and perform quick operations on them.

# Lambda function to find the shorter string between two words
shorter_word = lambda w1, w2: w1 if len(w1) < len(w2) else w2

print(shorter_word("Python", "AI"))

# Output will this: AI

Lambda Functions with Built-in Functions

Lambda functions become more powerful when you combine them with Python’s built-in functions like map(), filter(), and reduce().

1) map() with lambda: In this code, it converts a list of product prices into prices after adding 18% GST.

prices = [100, 250, 400, 90]

# Add 18% GST to each price
final_prices = list(map(lambda p: round(p * 1.18, 2), prices))

print(final_prices)

Output:

[118.0, 295.0, 472.0, 106.2]

2) filter() with lambda: In the code below, it keeps only those whose length is 5 or more characters.

names = ["Avi", "Rohan", "Meera", "Sid", "Varun"]

# Keep names with length >= 5
long_names = list(filter(lambda n: len(n) >= 5, names))

print(long_names)

Output:

['Rohan', 'Meera', 'Varun']
  • filter() checks each value using the lambda condition and keeps only those that match.

3) reduce(): We use reduce with lambda to small function for combining items and don’t write a full def function. For example:

from functools import reduce

numbers = [2, 3, 5]

# Multiply all values using reduce + lambda
result = reduce(lambda a, b: a * b, numbers)

print("Final Product:", result)

# Simple Output: Final Product: 30

How To Use Lambda Function In Sorting?

We are using a sorting algorithm to sort simple lists like numbers. But if you want to sort by a specific part of an item, like sorting a tuple by its second value, or sorting strings by length. In this case, we will use a lambda function.

sorted() does normal sorting, but key=lambda x: … tells Python which part of each item to look at while sorting.

Example: Sorting Students by Their Marks

students = [
("Riya", 78),
("Karan", 92),
("Mehul", 85)
]

# Sort by marks (2nd value in tuple)
sorted_students = sorted(students, key=lambda s: s[1])

print(sorted_students)

Output:

[('Riya', 78), ('Mehul', 85), ('Karan', 92)]

Limitations of Lambda Functions

  1. Single Expression: It cannot contain multiple statements or complex logic.
  2. Readability: It can reduce readability for more complex operations.
  3. No Documentation: Lambda functions do not support docstrings.

Real-World Use Cases of Lambda Functions

  1. Data Analysis: Use lambda functions for quick transformations of data.
  2. Web Development: You can simplify small operations like sorting or filtering in backend logic.
  3. Functional Programming: Ideal for functional programming paradigms.