DEV Community

Cover image for Python Lambda Functions Explained in 3 Easy Steps
Smit
Smit

Posted on

Python Lambda Functions Explained in 3 Easy Steps

Step 1: What is it ?

  • Think of a lambda as a small, one line function.
  • It's a quick and simple solution for small tasks, rather than using traditional functions defined with def.

Step 2: How does the function look?
Lambda x : x+2
This simple (and slightly different looking line) just means: "a function takes x and then returns x+2". That’s it!

Example:

add_two = lambda x : x+2
print(add_two(5)) #output: 7
Enter fullscreen mode Exit fullscreen mode

Explanation: We create a lambda function that takes a number x and adds 2 to it. We pass 5 as value and it returns 7.

Lambda function

Step 3: When to use a lambda function ?

It's very useful for quick, simple tasks like sorting, mapping, or filtering instead of writing a full function.

That’s it! A lambda function is just a short, fast function for simple jobs. And guess what? It’s called an anonymous function because it doesn’t have a name!

As promised, just 3 steps. Happy learning and happy coding!🎉💻

Top comments (2)

Collapse
 
vishal2796 profile image
Vishal Singh

Easy to understand. Great work.

Collapse
 
kashish_ profile image
Kashish

Explained nicely in layman terms