Programming me kabhi kabhi aisa hota hai ki tumhe list ke saare elements pe ek kaam karna ho, ya phir kuch elements ko condition ke hisaab se nikalna ho, ya sabko combine karke ek result banana ho.
Isi kaam ke liye Python me teen mast functions diye gaye hain:
👉 map()
👉 filter()
👉 reduce()
1. map() – Har element pe function lagao
map() ka kaam hai ek function ko sab elements pe apply karna aur result dena.
Example:
Tumhare paas numbers ki list hai aur tumhe sabka square chahiye.
x = lambda x: x**2
numbers =
squares = map(x, numbers)
squares = list(squares)
print(squares) #
⚡ Shortcut: map() = "Sab pe function lagao"
2. filter() – Condition ke hisaab se choose karo
filter() ka kaam hai condition check karna aur sirf wahi values dena jo pass ho.
Example:
Party ke liye sirf unko bulana hai jo 18 ya usse bade hain.
ages =
adults = list(filter(lambda x: x >= 18, ages))
print(adults) #
# Or
def is_adult(x):
return x >= 18
adults = list(filter(is_adult, ages))
print(adults) #
⚡ Shortcut: filter() = "Condition pass wale hi bachao"
3. reduce() – Sabko mila ke ek value banao
reduce() thoda alag hai, ye list ko process karke ek single output banata hai.
(Use karne ke liye functools import karna padta hai).
Example:
Tumhare paas paisa hai , aur tumhe total dekhna hai.
from functools import reduce
numbers =
total = reduce(lambda x, y: x + y, numbers)
print(total) # 15
⚡ Shortcut: reduce() = "Sabko ek me jodo"
Real-Life Example – Salary Calculation
Chalo ek thoda practical example dekhte hain.
Tumhare paas employees ki salaries list hai:
Ab kaam ye hai:
- Har salary pehle 10% tax cut karo →
map - Sirf 30,000 se upar wali salaries rakho →
filter - Sabko jod kar ek total salary nikalo →
reduce
from functools import reduce
salaries =
total = reduce(
lambda x, y: x + y,
filter(
lambda sal: sal > 30000,
map(lambda s: s - (s * 0.1), salaries)
)
)
print("Total Salary:", total) # 135000.0
Pythonic Way (List Comprehension + sum)
Upar wala code functional programming style me tha.
Agar tum Pythonic short aur readable code likhna chahte ho, to aise likh sakte ho:
salaries =
total = sum()
print("Total Salary:", total) # 135000.0
Dono ka result same hoga