Lambda Function in Python – Example Syntax
Lambda Function in Python – Example Syntax
ADVERTISEMENT
Perfect Freelance
Smile! You’re
Smile! You’re Perfect Freelance
Smile! You’re
about to get theabout to get the
about to get the
Hire an expert
Website design?
Freelance Services?
perfect shot. perfect shot.
perfect shot.
Lambda Function in
Python – Example
Syntax
Ilenia
:
Lambda functions ADVERTISEMENT
are anonymous
functions that can
contain only one
expression.
In Python, functions
are usually created like
this:
def my_func(a):
# function body
def double(x):
return x*2
def double(x):
return x*2
my_list = [1, 2, 3, 4, 5, 6]
new_list = list(map(double, my_list))
print(new_list) # [2, 4, 6, 8, 10, 12]
How to use
lambda
functions in
Python
ou use lambda functions when you need a
mall function for a short time – for example
s an argument of a higher order function like ADVERTISEMENT
map]
https://www.freecodecamp.org/news/python-
ap-function-how-to-map-a-list-in-python-
-0-with-example-code/) or filter .
Example 1
For example, you could
write a lambda
:
write a lambda
my_list = [1, 2, 3, 4, 5, 6]
new_list = list(map(lambda x: x*2, my_list))
print(new_list) # [2, 4, 6, 8, 10, 12]
Example 2
Or you could write a
lambda function that
:
lambda function that
checks if a number is
Example 3
You can also return a
lambda function from
:
lambda function from
a function.
Instead of creating
multiple functions, you
could create a function
multiplyBy as below,
and then call this
function multiple
times with different
arguments to create
the functions that
double, triple, and so
on.
double = multiplyBy(2)
:
double = multiplyBy(2)
triple = muliplyBy(3)
times10 = multiplyBy(10)
double(6)
> 12
triple(5)
> 15
times10(12)
> 120
Using a lambda
function uses half the
ADVERTISEMENT
lines and makes it
more readable.
Conclusion
Lambda functions are
a compact way to
write functions if your
function includes only
one small expression.
They are not usually
something that
beginner coders use,
but here you have
:
seen how you can
Ilenia
Read more posts.
ADVERTISEMENT
:
freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization
(United States Federal Tax Identification Number: 82-0779546 )
Our mission: to help people learn to code for free. We accomplish this by creating
thousands of videos, articles, and interactive coding lessons - all freely available to the
public.
Donations to freeCodeCamp go toward our education initiatives, and help pay for
servers, services, and staff.
Mobile App
Our Charity
About Alumni Network Open Source Shop Support Sponsors Academic Honesty