A lambda function in Python is a small, anonymous function that is defined using the lambda
keyword. It’s great for short, one-time use operations without the need to define a full function
using def
lambda arguments: expression
Purpose of Lambda:
Saves space – No need for full function definitions.
Works inline – Fits perfectly into built-in functions (map(), filter(), sorted()).
Boosts readability – Great for small, quick operations.
def double(x): return x * 2
def square(x): return x * x
print(square(double(3))) #square(6)
Recursive Function - a function that calls itself
Base condition is mandatory
def fact(n):
if n<=0:
return 0
if n==1:
return 1
return n * fact(n-1)
print(fact(n=4))
() - intrepreter will look function or it will assume as variable
Lambda
return function object
expression must be single line
power = lambda x, y=3: x*y
print(power(3,4))
def power_of(n): # power_of(2) n= 2
return lambda x:x**n # lambda ( return type is Function as object) lambda x : x ** 2
square = power_of(2) # lambda x : x ** 2
cube = power_of(3) # lambda x : x ** 3
print(square(4))
print(cube(4))
lis = lambda x : [print(i) for i in x ]
lis("Python")
Usage Code Example
Add two numbers lambda a, b: a + b
Sort by last char sorted(words, key=lambda x: x[-1])
Filter even nums filter(lambda x: x%2==0, nums)
Map square map(lambda x: x*x, nums)
def power(x,y=3):
return x*y
Map:
applies an short function to all elements,
It returns an map object
suyntax: map(function,iterable[,iterable]) -> one or more iterable ( provided function should
take more argument)
s = ['1', '2', '3', '4']
res = map(int, s)
# for i in s:
# int(i)
print(list(res))
def double(val):
return val*2
d= [1,2,3,4]
res= map( double, d)
d= [1,2,3,4]
res= list(map( lambda val: val*2 , d))
print(res)
d= [1,2,3,4]
d1=[4,5,6,7]
res= list(map( lambda x,y : x+y , d,d1))
print(res)
filter() is used to filter out elements from an iterable (like a list, tuple, etc.)
for which a function returns True.
returns filter object
syntax: filter( function, sequence/iterable)
lis=list(range(1,25)) # [1,2,3,4, to 24 ]
res= filter(lambda x: x%2==0 , lis)
print(list(res))
# filter truthy value : None, False, "", [],(),{} etc
data = [0,'',"Python",None,False,42,[],()]
data = list(filter(None, data))
print(data)
def is_prime(n): #5
if n<2:
return False
for i in range(2, int(n**0.5)+1 ):
if n%i==0:
return False
return True
primes = list(filter(is_prime, range(20)))
print(primes)
reduce() reduces a sequence of elements into a single value by applying a binary function
cumulatively.
Syntax: reduce(function, iterable , initializer(optional ) )
from functools import reduce
def func(x,y):
return x+y
nums= [1,2,3,4,5]
result = reduce(func, nums )
# 1,2 = (3)
# 3, 3 = 6
# 6, 4 = 10
# 10, 5 = 15
print(result)
nums= [1,2,3,4,5]
result = reduce(lambda x,y: x+y , nums, 10 )
# 10,1 = (11)
# 11, 2 = 13
# 13, 3 = 16
# 16, 4 = 20
# 20,5 = 25
print(result)
nums= [5,4,3] # -> 543
# 5*10 + 4 = 54 x =5,y=4 = x*10+y
# 54 *10 + 3 = 54
result = reduce(lambda x,y: x*10 + y , nums)
print(result)
from functools import reduce
nums= [5,4,3] # -> 543
# 5*10 + 4 = 54 x =5,y=4 = x*10+y
# 54 *10 + 3 = 54
result = reduce(lambda x,y: x*10 + y , nums)
print(result)
Valid Parentheses:
class Solution:
def isValid(self, s: str) -> bool:
lis = []
for ch in s:
if ch == '(' or ch == '{' or ch == '[':
lis.append(ch)
elif ch == ')':
if not lis or lis[-1] != '(':
return False
lis.pop()
elif ch == '}':
if not lis or lis[-1] != '{':
return False
lis.pop()
elif ch == ']':
if not lis or lis[-1] != '[':
return False
lis.pop()
return len(lis) == 0