Prahlad Inala
Prahlad Inala

Follow

Prahlad Inala

Follow
Lambda Expressions in Python

Lambda Expressions in Python

Prahlad Inala's photo
Prahlad Inala
ยทJul 18, 2021ยท

2 min read

Play this article

What are Lambda Expressions in Python?

Lambda Expression is a one-line shorthand to create a function without giving it any name.

Example

#its looks like
lambda x: x**2

# assign lambda to a variable
square_lambda=lambda x: x**2

lambda is a 'function' type.

we can invoke this as a function.

Lambda expression comes in handy when you want to create a function that you will use only one time. For example the functions we pass to the built Map (or) filter functions.

If your function could be used in many places then it should be defined like a normal function but instead, if your function is for a one-time use then use Lambda Expressions.

Lambda expressions can be used with a map function to reduce code and make it more readable.

for example, let's say we want to double every element in a list using the map function.

Without using lambda expressions:

def double_it(num):
    return num*2
my_list=[1,2,3,4,5]
new_list=map(double_it,my_list)

Using lambda expressions

my_list=[1,2,3,4,5]
(# lambda used to double each element in the list)
new_list=map(lambda x:x*2,my_list)

Lambda expressions can be used with the filter function to reduce code and make it more readable.

we will filter a list of numbers to have only odd numbers using the filter function.

Without using lambda expressions:

def is_odd(num):
    return num%2==1
my_list=[1,2,3,4,5]
new_list=filter(is_odd,my_list)

Using lambda expressions

my_list=[1,2,3,4,5]
new_list=filter(lambda num:num%2==1,my_list)

Did you find this article valuable?

Support Prahlad Inala by becoming a sponsor. Any amount is appreciated!

See recent sponsors |ย Learn more about Hashnode Sponsors
ย 
Share this