A lambda function in Python is a small, anonymous function defined with the lambda
keyword. It can take any number of arguments but can have only one expression. Lambda functions are useful when a short, throwaway function is needed.
Python में lambda function एक छोटा, गुमनाम function होता है जिसे lambda
keyword से बनाया जाता है। यह कई arguments ले सकता है लेकिन केवल एक expression हो सकता है। जब short और temporary function चाहिए, तब इसका उपयोग किया जाता है।
map()
, filter()
, reduce()
map()
, filter()
, reduce()
जैसी functions में उपयोगीadd = lambda a, b: a + b
print(add(5, 3))
Output:
8
square = lambda x: x * x
print(square(6))
Output:
36
is_even = lambda x: x % 2 == 0
print(is_even(4))
Output:
True
pairs = [(1, 5), (2, 3), (4, 1)]
pairs.sort(key=lambda x: x[1])
print(pairs)
Output:
[(4, 1), (2, 3), (1, 5)]
nums = [1, 2, 3]
squares = list(map(lambda x: x*x, nums))
print(squares)
Output:
[1, 4, 9]
nums = [1, 2, 3, 4]
evens = list(filter(lambda x: x%2==0, nums))
print(evens)
Output:
[2, 4]
from functools import reduce
nums = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, nums)
print(product)
Output:
24
maximum = lambda a, b: a if a > b else b
print(maximum(10, 15))
Output:
15
c_to_f = lambda c: (c * 9/5) + 32
print(c_to_f(0))
Output:
32.0
length = lambda s: len(s)
print(length("Python"))
Output:
6