paint-brush
A Brief Introduction to Lambda Expressions in Pythonby@aswinbarath
789 reads
789 reads

A Brief Introduction to Lambda Expressions in Python

by Aswin BarathFebruary 6th, 2021
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Lambda expressions in python are one-time anonymous functions which we don’t need more than once.

Company Mentioned

Mention Thumbnail
featured image - A Brief Introduction to Lambda Expressions in Python
Aswin Barath HackerNoon profile picture

Lambda expressions in python are one-time anonymous functions which we don’t need more than once.

And according to W3Schools, "A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression."

Consider the following example where we use a function to multiply a list of numbers with the mathematical constant pi:

Output:

[3.14, 6.28, 9.42]

What if I say that we could do all of this in one line. Well, it turns out we can do it. We can convert the above example into a single line of code using Lambda expressions.

Output:

[3.14, 6.28, 9.42]

Lambda function

Syntax - lambda arguments : expression

A lambda function can take any number of arguments, but can only have one expression:

Output:

94

Why do we need to use Lambda functions?

  • Well, it contributes to the code by reducing the number of lines of functions which we may use only once.
  • To take it to the next level, we can return an anonymous function inside another example:

Output:

62.800000000000004
119.32000000000001
31.400000000000002

As you can see, we got to use the same function to calculate different values. You get to create a function definition that takes one argument, and that argument will be multiplied with an unknown number (which you can specify in the future).

That’s the power of lambda expressions.

Code along and learn more…

Also published at https://dev.to/aswin2001barath/lambda-expressions-in-python-5ffg