Skip to content

Cool Functions

Lambda Function💡

Lambda Functions

A lambda function is a small anonymous (nameless) function defined using the keyword lambda. It can take any number of arguments, but can only have one expression, which is implicitly returned. They are often used for small, single-operation tasks, especially when passed as arguments to higher-order functions.

Syntax: lambda arguments: expression

1
2
3
4
# square

sq = lambda x :x**2
sq(5)
Output
25

Lambda functions can take multiple arguments.

1
2
3
# x,y -> x+y
a = lambda x,y:x+y
a(5,2)
Output
7

The expression is evaluated and returned.

1
2
3
4
# check if a string has 'a'

a = lambda s : 'a' in s
a('hello')
Output
False

Returns a boolean result.

1
2
3
4
# is_even

is_even = lambda x : x%2==0
is_even(5)
Output
False

Lambda functions support conditional expressions (ternary operators).

is_even = lambda x :'even' if x%2==0 else 'odd'
is_even(5)
Output
'odd'


Higher Order Function ⬆️

Higher Order Function

A Higher Order Function (HOF) is a function that either takes one or more functions as arguments or returns a function as its result. map, filter, and reduce are common HOFs.

This custom function demonstrates a basic higher-order function that takes another function (func) and a list (arg_list) as input.

def square(x):
    return x**2

def cube(x):
    return x**3

def my_map(func,arg_list): # my_map is a HOF
    result = []
    for i in arg_list:
        result.append(func(i))
    return result
Output


Map

The map() function applies a given function to all items in an input list (or other iterable) and returns a map object (which can be converted to a list).

Syntax: map(function, iterable)

Mapping Examples

1
2
3
4
5
# square the items of a list
def square(x):
    return x**2

list(map(square,[1,2,3,4,5]))
Output
[1, 4, 9, 16, 25]

list(map(lambda x:x**2, [1,2,3,4,5]))
Output
[1, 4, 9, 16, 25]

1
2
3
# odd/even labelling of list items
L = [1,2,3,4,5]
list(map(lambda x:'even' if x%2 == 0 else 'odd',L))
Output
['odd', 'even', 'odd', 'even', 'odd']

1
2
3
4
5
6
7
8
9
# fetch gender from a list of dict

users = [
    { 'name':'Rahul', 'age':45, 'gender':'male' },
    { 'name':'Nitish', 'age':33, 'gender':'male' },
    { 'name':'Ankita', 'age':50, 'gender':'female' }
]

list(map(lambda users:users['gender'],users))
Output
['male', 'male', 'female']

1
2
3
4
5
6
users = [
    { 'name':'Rahul', 'age':45, 'gender':'male' },
    { 'name':'Nitish', 'age':33, 'gender':'male' },
    { 'name':'Ankita', 'age':50, 'gender':'female' }
]
list(map(lambda users: users['age'], users))
Output
[45, 33, 50]


Filter

The filter() function constructs an iterator from elements of an iterable for which a function returns true.

Syntax: filter(function, iterable)

Filtering Examples

1
2
3
# numbers greater than 5
L = [3,4,5,6,7]
list(filter(lambda x:x>5,L))
Output
[6, 7]

1
2
3
4
# fetch fruits starting with 'a'
fruits = ['apple','guava','cherry']

list(filter(lambda x:x.startswith('a'),fruits))
Output
['apple']

Reduce

The reduce() function applies a function cumulatively to the items of an iterable, reducing the iterable to a single value. It is located in the functools module.

Syntax: functools.reduce(function, iterable)

Reduce Examples

Accumulates the sum: ( ( (1+2)+3 )+4 )+5

1
2
3
# sum of all item
import functools
functools.reduce(lambda x,y:x+y,[1,2,3,4,5])
Output
15

The lambda function returns the greater of the two values being compared at each step, accumulating the maximum value.

1
2
3
4
# find max (The example in the prompt is titled 'find min' but the lambda x if x>y else y finds the max)
import functools

functools.reduce(lambda x,y:x if x>y else y,[23,11,45,10,1])
Output
45