Python Programming · Lesson 11 of 15 · Updated ·
List Comprehensions, lambda, map, filter and Recursion in Python
Once you know loops and functions, Python gives you shorter ways to write common patterns. Interviewers like candidates who use them well.
1. List comprehensions
Pattern: [expression for item in iterable if condition]
nums = [1, 2, 3, 4, 5, 6]
print([n * n for n in nums])
print([n for n in nums if n % 2 == 0])
print([w.upper() for w in ["hi", "there"]])
print(["even" if n % 2 == 0 else "odd" for n in nums[:3]])
[1, 4, 9, 16, 25, 36]
[2, 4, 6]
['HI', 'THERE']
['odd', 'even', 'odd']
Also works for sets {…} and dicts {k: v …}. Use comprehensions for simple transformations; for complex logic, a normal loop is clearer.
2. lambda: tiny one-line functions
square = lambda x: x * x
print(square(7))
students = [("Asha", 92), ("Ravi", 74), ("Neha", 85)]
students.sort(key=lambda s: s[1])
print(students)
49
[('Ravi', 74), ('Neha', 85), ('Asha', 92)]
lambda is mostly used as a quick key= for sorting, max, min.
3. map and filter
map(f, items)applies f to every item.filter(f, items)keeps items where f returns True.
prices = [100, 250, 80]
print(list(map(lambda p: p * 1.18, prices)))
print(list(filter(lambda p: p >= 100, prices)))
[118.0, 295.0, 94.39999999999999]
[100, 250]
(See the tiny decimal error in 94.39999…? That's normal floating-point behaviour. Use round(x, 2) for money.)
4. zip, any, all
names = ["Asha", "Ravi"]
marks = [92, 74]
for n, m in zip(names, marks):
print(n, m)
print(dict(zip(names, marks)))
print(any(m < 40 for m in marks), all(m >= 70 for m in marks))
Asha 92
Ravi 74
{'Asha': 92, 'Ravi': 74}
False True
5. Recursion: a function that calls itself
Every recursive function needs a base case (when to stop) and a smaller step.
def factorial(n):
if n <= 1: # base case
return 1
return n * factorial(n - 1)
print(factorial(5))
120
How it unfolds: factorial(5) = 5 × factorial(4) = 5 × 4 × factorial(3) … = 5 × 4 × 3 × 2 × 1 = 120.
Fibonacci — and why memoisation matters
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print([fib(i) for i in range(10)], fib(80))
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34] 23416728348467685
Without @lru_cache, fib(80) would take far too long — the same values get recalculated millions of times. Our DSA recursion tutorial goes deeper.
Common mistakes
- Writing very long comprehensions that nobody can read.
- Forgetting
list()aroundmap/filterwhen you want to print the result. - Recursion with no base case →
RecursionError.
Quick recap
[expr for x in items if cond]replaces build-a-list loops.lambda x: …for short key functions.maptransforms,filterselects,zippairs,any/allcheck.- Recursion = base case + smaller step; cache repeated work.