DEV Community

Cover image for Lambda expressions in python
Aswin Barath
Aswin Barath

Posted on • Edited on

3 1 1 1 1

Lambda expressions in python

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

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

Alt Text

Output:

[3.14, 6.28, 9.42]
Enter fullscreen mode Exit fullscreen mode

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.

Alt Text

Output:

[3.14, 6.28, 9.42]
Enter fullscreen mode Exit fullscreen mode

Lambda function

Syntax: lambda arguments : expression

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

Alt Text

Output:

94
Enter fullscreen mode Exit fullscreen mode

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:

Alt Text

Output:

62.800000000000004
119.32000000000001
31.400000000000002
Enter fullscreen mode Exit fullscreen mode

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.

Best Resources

Who Am I?

I’m Aswin Barath, a Software Engineering Nerd who loves building Web Applications, now sharing my knowledge through Blogging during the busy time of my freelancing work life. Here’s the link to all of my socials categorized by platforms under one place: https://linktr.ee/AswinBarath

Thank you so much for reading my blog🙂.

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay