DEV Community

Guru prasanna
Guru prasanna

Posted on

Python Day - 31 Types of Functions

Types of functions:

Lambda Function:

--> A lambda function in Python is an anonymous (unnamed) function defined using the lambda keyword.

--> A lambda function can take any number of arguments, but can only have one expression.

Syntax

lambda arguments : expression

Image description

When to Use Lambda Functions?

--> When you need a small function for a short period.
--> When passing functions as arguments (e.g., in map(), filter(), sorted(), etc.).
--> when you need a quick one-line function without a name and without writing a full def function.

Step by step conversion of Normal function --> Lambda Function:

Normal function:

def add(no1,no2):
    return no1+no2
result=add(100,200)
print(result)
Enter fullscreen mode Exit fullscreen mode

Lambda Function:
1) Remove def

add(no1,no2):
    return no1+no2
Enter fullscreen mode Exit fullscreen mode

2) Remove function name

(no1,no2):
    return no1+no2
Enter fullscreen mode Exit fullscreen mode

3) Remove return and add lambda keyword in front

lambda no1,no2:no1+no2
Enter fullscreen mode Exit fullscreen mode

4) Assign the Lambda Function to a Variable and Call the Lambda Function

result = lambda no1,no2 : no1+no2
print(result(100,200))
Enter fullscreen mode Exit fullscreen mode

Output:
300

Example:

#Normal function
def find_bigger(no1,no2):  
    if no1>no2:
        return no1
    else:
        return no2

num = find_bigger(10,5)
print(num)

#Lambda function
bigger = lambda no1,no2:  no1 if no1>no2 else no2
print(bigger(10,5))
Enter fullscreen mode Exit fullscreen mode

Output:

10
10
Enter fullscreen mode Exit fullscreen mode

Higher-order functions:

 In Python, `map()`, `filter()`, and `reduce()` are called higher-order functions because they take another function (like a lambda function) as an argument and apply it to an iterable (like a list or tuple).
Enter fullscreen mode Exit fullscreen mode

Common Syntax:

Syntax: filter or map or reduce(function, iterable)

filter(): Filters elements based on a condition (returns only True values).

Example:

#Normal function
def check(no):
    if no%5==0:
        return True
    return False

#Lambda function
lambda no:no%5==0 

l = [10,20,2,3,4,5,67,8,9,15,25,32,33,34,35]

#function passed as an argument
print(list(filter(check, l))) #normal function 
print(list(filter(lambda no:no%5==0, l))) #lambda function 
Enter fullscreen mode Exit fullscreen mode

Output:

[10, 20, 5, 15, 25, 35]
[10, 20, 5, 15, 25, 35]
Enter fullscreen mode Exit fullscreen mode

map(): Applies a function to each element in an iterable (e.g., list, tuple).

Example:

#Normal function
l = [10,20,30,40,50]

def find_power(no):
    return no**2

#Lambda function
lambda no : no**2, l

#function passed as an argument
print(map(find_power, l))#map object
print(list(map(find_power, l))) #normal function--> map to list
print(list(map(lambda no : no**2, l))) #lambda function 
Enter fullscreen mode Exit fullscreen mode

Output:

<map object at 0x7f85bbe8a380>
[100, 400, 900, 1600, 2500]
[100, 400, 900, 1600, 2500]
Enter fullscreen mode Exit fullscreen mode

reduce(): Performs a cumulative operation (e.g., sum, multiplication) on an iterable.

Example:

from functools import *
#reduce

l = [10,20,30,40]

def find_total(total, l):
    for no in l:
        total = total + no 
    return total


print(find_total(0,l))

print(reduce(lambda total, no:total+no , l))
Enter fullscreen mode Exit fullscreen mode

Output:

100
100
Enter fullscreen mode Exit fullscreen mode

Function Aliasing

--> Function aliasing means giving an existing function another name (alias) so that it can be called using a different name.
--> This does not create a new function but refers to the same function using another variable.

Example:

def greet(name):
    print('Welcome', name)

greet('Guru')

display = greet
print(id(greet))
print(id(display))

display('Pritha')
Enter fullscreen mode Exit fullscreen mode

Output:

Welcome Guru
135055965790880
135055965790880
Welcome Pritha
Enter fullscreen mode Exit fullscreen mode

Decorator Functions

--> A decorator is a special function that modifies the behavior of another function without changing its actual code.
--> It takes another function as an argument and returns a new function with enhanced functionality.
--> @ symbol is used to apply decorators.

Example: 1

def decor(func1):
    def inner(name):
        if name == 'Guido':
            print('Oh! Unexpected Guest, Welcome Mr.', name)
        else:
            func1(name)
    return inner

@decor  #Decorator Function
def greet(name):
    print('Welcome', name)

greet('Guru')
greet('Muthu')
greet('Pritha')

greet('Guido') 
Enter fullscreen mode Exit fullscreen mode

Output:

Welcome Guru
Welcome Muthu
Welcome Pritha
Oh! Unexpected Guest, Welcome Mr. Guido
Enter fullscreen mode Exit fullscreen mode

Example: 2

def decor1(func1):
    def inner():
        no = func1()
        return no
    return inner

def decor(func1):
    def inner():
        no = func1()
        return no ** 2
    return inner

@decor1
@decor  #Decorator Function
def greet():
    return 100

print(greet())
Enter fullscreen mode Exit fullscreen mode

Output:

10000
Enter fullscreen mode Exit fullscreen mode

Common Use Cases of Decorators

✔ Logging: Track function execution
✔ Authentication: Restrict access based on conditions
✔ Timing Functions: Measure execution time
✔ Caching: Store results for performance

Generator functions:

--> A generator function is a special type of function that returns an iterator using the yield keyword instead of return.
--> It allows you to generate values one at a time instead of storing them all in memory at once.

Example: 1

def generator_demo():
    yield 100
    yield 200
    yield 'ABCD'

result = generator_demo()
print(type(result))

print(next(result))
print(next(result))
print(next(result))
Enter fullscreen mode Exit fullscreen mode

Output:

<class 'generator'>
100
200
ABCD
Enter fullscreen mode Exit fullscreen mode

Example: 2

def display_first_n_numbers(num):
    no = 1
    while no<=num:
        yield no
        no+=1

result = display_first_n_numbers(5)
print(type(result))
for number in result:
    print(number)
Enter fullscreen mode Exit fullscreen mode

Output:

<class 'generator'>
1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

Key Benefits of Generators

✔ Memory Efficient: Generates values on demand, avoids storing large datasets.
✔ Faster Execution: No need to create a full list before using values.
✔ Lazy Evaluation: Computes values only when needed.
✔ Infinite Sequences: Useful for streaming data or generating infinite numbers.

Top comments (0)