Python lambda functions are an invaluable feature. One of the benefits of using Python is that it facilitates a relatively compact code structure compared to other programming languages. This means getting so much more done with fewer lines of code.

This isn’t always the case, however. If you’re not aware of the tools python provided in order to achieve this, it is very easy to write verbose code that defeats the point of picking Python for its “compactness”.

One such tool is the lambda function. These allow us to create anonymous functions in python. If you’ve read good python programmers’ code before, you might have come across something that looks like this:

add = lambda a,b : a + b

The code above might look a bit confusing, let me clarify the syntax of a lambda function by breaking it down into its components. Lambda functions have 3 components: the ‘lambda’ keyword (of course), the set of arguments, and an expression.

lambda [(optional) arguments] : [expression]

The Rules

Before we go into detail about the implementation of lambda functions, let’s first discuss their rules:

  1. Lambda functions are nameless (unless assigned to a variable). You cannot assign a function name after the ‘lambda’ keyword’ as you would with the ‘def’ keyword.
  2. Arguments are optional. Lambda functions can be defined without passing any arguments, just like a regular function.
  3. Lambda functions can only have one expression.
  4. Just like a regular function, you can return anything from a lambda function. It is also possible to return nothing.
  5. Lambda functions can be assigned to variables for repeated use. This is the only way to name a lambda function.
  6. Lambda functions can be returned from regular functions.
  7. Lambda functions can return other lambda functions.

Why Use Lambda Functions?

If you have never used lambda functions before, you probably think that you would do just fine without them, and you’d be right. However, as I’ve stated before, they play an important role in making sure we maintain clean, compact and pythonic code.

Lambda functions are most useful in situations where an anonymous function is required for single-use or repeated use.

#python3 #data #lambda-function #python #functions-in-python

Python Lambda Functions
3.50 GEEK