🟢 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
keyinsorted,map,filter. - For anything longer than one expression, use a normal
definstead.
Common Mistakes
- Trying to put multiple statements in a lambda — only one expression is allowed.
- Forgetting
list()aroundmap/filter(they return objects, not lists).
Practice Tasks
- Write a lambda that cubes a number.
- Use
mapwith a lambda to double every item in a list. - Use
filterto keep only words longer than 4 letters. - 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
deffor anything longer.
💻 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.