🟢 Beginner  ·  Lesson 11

Lambda, map, filter and reduce

What is a Lambda?

A lambda is a tiny, one-line function with no name (anonymous). It is handy for short tasks you do not want to write a full def for.

Lambda Syntax

Python – lambda
# Normal function
def square(x):
    return x * x

# Same thing as a lambda
square = lambda x: x * x

print(square(5))
25

Pattern: lambda arguments: expression. The expression's value is returned automatically.

Program 1: Simple Lambda

Python – simple.py
add = lambda a, b: a + b
is_even = lambda n: n % 2 == 0

print(add(3, 4))
print(is_even(10))
7 True

Program 2: Lambda with map()

map() applies a function to every item in a list.

Python – map.py
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x * x, nums))
print(squares)
[1, 4, 9, 16]

The lambda squares each number; map runs it across the whole list.

Program 3: Lambda with filter()

filter() keeps only items where the function returns True.

Python – filter.py
nums = [5, 12, 8, 21, 3]
big = list(filter(lambda x: x > 10, nums))
print(big)
[12, 21]

Program 4: Lambda with sorted()

A lambda can tell sorted() what to sort by.

Python – sortby.py
students = [("Aman", 88), ("Riya", 95), ("Karan", 79)]
# sort by marks (the second item)
top = sorted(students, key=lambda s: s[1], reverse=True)
print(top)
[('Riya', 95), ('Aman', 88), ('Karan', 79)]

key=lambda s: s[1] tells sorted to use the marks for ordering.

When to Use Lambda

  • For short, throwaway functions used once.
  • As the key in sorted, map, filter.
  • For anything longer than one expression, use a normal def instead.

Common Mistakes

  • Trying to put multiple statements in a lambda — only one expression is allowed.
  • Forgetting list() around map/filter (they return objects, not lists).

Practice Tasks

  1. Write a lambda that cubes a number.
  2. Use map with a lambda to double every item in a list.
  3. Use filter to keep only words longer than 4 letters.
  4. Sort a list of names by their length using a lambda.

Summary

  • Lambda is a one-line anonymous function: lambda args: expression.
  • Common with map, filter, sorted.
  • Use a normal def for anything longer.
← Back to Python Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.