Lambda Functions in Python

Lambda Functions in Python

Anonymous Functions

Β·

3 min read

Namaste Coders πŸ‘©β€πŸ’»

Before starting have a glance on the below article to know about functions in Python πŸ‘‡

Built-in Functions User Defined Functions

In this article, we will discuss lambda functions in Python. These are one liner 😎 functions in Python.

What are Lambda Functions πŸ€”?

Lambda functions or anonymous functions provide a sugary syntax to write functions in one line in Python.

To define an anonymous function we use the keyword lambda in Python.

It can have any number of arguments/parameters but should contain only one expression which has to be returned.

In Lambda function there is no def or return keyword used.

Syntax

lambda  parameter_list: expression

Example

#Find square of a number using anonymous function
square=lambda x: x*x
num=5
print("Square of number is: ",square(num))

#Area of a rectangle
area=lambda l,b: l*b
l=4
b=5
print("area of rectangle is : ",area(l,b))

#Square of number is:  25
#area of rectangle is :  20

Using Conditionals in Lambda

Syntax :

lambda  parameter_list: if statement (if condition) else else statement

Example

max = lambda a,b : a if a>b else b
print(max(5,4))

#5
tables = [lambda x=x: x*10 for x in range(1, 11)]

for t in tables:
    print(t() , end =" ")

#10 20 30 40 50 60 70 80 90 100

Higher Order Functions

Higher Order Functions (HOF) are the functions in which another function is passed as an argument. Lambda Functions are passed as an argument in these functions.

  • map function

map function computes certain operation on an iterable(list) and returns new list.

Syntax

map(lambda function , iterable)
#returns a list 
#even nums square and odd nums cube 
nums = [1,2,3,4,5,6]

nums_list = list(map(lambda x :x**2 if x%2==0 else x**3 , nums))
print(nums_list)

#[1, 4, 27, 16, 125, 36]
  • filter function

As the name suggests, it filters the element from the list on the basis of the condition specified in the function.

Syntax

filter(lambda function , iterable)

Example

nums = [1,2,3,4,5,6]

# Filters all the even nums
even = list(filter(lambda x : x%2==0 , nums))
print(even)

#[2, 4, 6]
  • reduce function

It accumulates all the values into a single value. Like performing addition or multiplication among all the elements in the list and returning one result.

Syntax

reduce(lambda function , iterable)

Example

nums = [1,2,3,4,5,6]

# importing to reduce function
from functools import reduce

# multiplying all the elements
mul = reduce(lambda a,b : a*b , nums)
print(mul)

#720

P.S. : Will continue with the functions and discuss more in upcoming articles. Stay tunedπŸ‘§

The End

I hope you enjoyed the article and had a good learning experience.

Follow for more articles and keep sharingπŸ‘©

Keep coding

Python blogs

Linkedin

hashnode blogs

Did you find this article valuable?

Support akshita garg's blog by becoming a sponsor. Any amount is appreciated!

Β