Lambda Functions


In Python, lambda functions are small, anonymous functions defined using the lambda keyword. Unlike regular functions defined with def, lambda functions are single-line, concise, and generally used for short operations. They are widely used in functional programming, for tasks like sorting, filtering, mapping, and quick calculations.

This tutorial will cover defining lambda functions, syntax, arguments, return values, practical uses, and common applications.

What is a Lambda Function?

A lambda function is an anonymous function in Python that can have any number of input arguments but only one expression. The expression is evaluated and returned automatically.

Basic syntax:

lambda arguments: expression
  • lambda – keyword to define the function

  • arguments – input parameters (can be multiple)

  • expression – single expression whose value is returned

Assigning a Lambda Function to a Variable

You can assign a lambda function to a variable, which allows you to call it like a regular function:

square = lambda x: x ** 2
print(square(5))  # Output: 25

Here, x is the input parameter and x ** 2 is the expression returned.

Lambda Functions with Multiple Arguments

Lambda functions can take multiple arguments separated by commas:

add = lambda a, b: a + b
print(add(10, 5))  # Output: 15

You can include as many arguments as needed, but the function must remain a single expression.

Using Lambda Functions with map()

The map() function applies a given function to all items in an iterable (like a list):

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

Here, the lambda function calculates the square of each number in the list.

Using Lambda Functions with filter()

The filter() function selects elements from an iterable that satisfy a condition:

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # Output: [2, 4, 6]

The lambda function checks for even numbers and returns only those that satisfy the condition.

Using Lambda Functions with reduce()

The reduce() function from the functools module reduces a list to a single value by applying a function cumulatively:

from functools import reduce

numbers = [1, 2, 3, 4, 5]
sum_total = reduce(lambda x, y: x + y, numbers)
print(sum_total)  # Output: 15

Here, the lambda function adds numbers cumulatively to produce a single sum.

Using Lambda Functions with sorted()

Lambda functions can be used as the key in sorting:

students = [("Ananya", 22), ("Meera", 20), ("Riya", 25)]
sorted_students = sorted(students, key=lambda x: x[1])
print(sorted_students)
# Output: [('Meera', 20), ('Ananya', 22), ('Riya', 25)]

This sorts the list of tuples by the second element (age).

Advantages of Lambda Functions

  1. Concise code – Defined in a single line

  2. No need for naming – Anonymous and useful for short tasks

  3. Useful with functional programming – Works with map(), filter(), reduce(), and sorted()

  4. Inline usage – Ideal for quick operations without defining a full function

Limitations of Lambda Functions

  • Can only contain a single expression

  • Cannot include multiple statements or annotations

  • Less readable for complex operations

  • Typically used for small, simple functions

Practical Examples

  1. Square a number:

square = lambda x: x ** 2
print(square(6))  # Output: 36
  1. Add two numbers:

add = lambda a, b: a + b
print(add(10, 15))  # Output: 25
  1. Filter even numbers from a list:

numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)  # Output: [2, 4, 6]
  1. Square each number in a list using map():

numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, numbers))
print(squared)  # Output: [1, 4, 9, 16]
  1. Sum all numbers using reduce():

from functools import reduce
numbers = [1, 2, 3, 4, 5]
total = reduce(lambda x, y: x + y, numbers)
print(total)  # Output: 15
  1. Sort a list of tuples by the second element:

students = [("Ananya", 22), ("Meera", 20), ("Riya", 25)]
sorted_list = sorted(students, key=lambda x: x[1])
print(sorted_list)
  1. Convert a list of strings to uppercase:

names = ["ananya", "meera", "riya"]
upper_names = list(map(lambda x: x.upper(), names))
print(upper_names)  # Output: ['ANANYA', 'MEERA', 'RIYA']
  1. Filter strings with length greater than 4:

words = ["apple", "bat", "cat", "dolphin"]
long_words = list(filter(lambda x: len(x) > 4, words))
print(long_words)  # Output: ['apple', 'dolphin']
  1. Find the maximum number in a list of tuples using the second element:

numbers = [(1, 10), (2, 5), (3, 20)]
max_item = max(numbers, key=lambda x: x[1])
print(max_item)  # Output: (3, 20)
  1. Check if numbers are positive or negative:

nums = [-2, 3, -1, 5]
signs = list(map(lambda x: "Positive" if x > 0 else "Negative", nums))
print(signs)  # Output: ['Negative', 'Positive', 'Negative', 'Positive']

Summary of the Tutorial

Python lambda functions are concise, anonymous functions that allow you to write quick, single-line operations. They are most useful when working with functional programming tools like map(), filter(), reduce(), and sorting operations.

Key points:

  • Defined using lambda keyword

  • Can have multiple arguments but only one expression

  • Automatically return the result of the expression

  • Often used for short-term, inline operations

By mastering lambda functions, you can write cleaner, more efficient Python code for tasks that don’t require full, named functions.


Practice Questions

Q1. Write a Python program to create a lambda function that multiplies two numbers.

Q2. Write a Python program to create a lambda function that checks if a number is even.

Q3. Write a Python program to use a lambda function to return the cube of a number.

Q4. Write a Python program to use lambda with map() to double all values in a list.

Q5. Write a Python program to filter out numbers greater than 10 from a list using lambda and filter().

Q6. Write a Python program to sort a list of names by length using a lambda function.

Q7. Write a Python program to create a function that returns a lambda which triples a number.

Q8. Write a Python program to combine def and lambda to create dynamic multipliers, like make_multiplier(5)(2) → 10.

Q9. Write a Python program to use lambda with filter() to find multiples of 3 in a list.

Q10. Write a Python program to create a lambda function that takes 3 parameters and returns their sum.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top