Lambda Syntax in Python & its functions

Lambda Syntax in Python & its functions
Lambda Syntax in Python & its functions

Python and other languages like C++, Java and C# have had lambda functions added to their syntax. Whereas languages like LISP or the ML family of languages like Haskell, OCaml use lambdas as a core concept.

In Python, lambdas are little, anonymous functions, subject to a more restrictive but more concise syntax than regular Python functions. So in Python, we use the lambda keyword to declare an anonymous function, which is why we refer to them as “Lambda functions”. An anonymous function refers to a function declared with no name.  This anonymous function is created with the lambda keyword.  Although syntactically they look different, lambda functions behave in the same way as regular functions that are declared using the def keyword.

The following are the characteristics of Python lambda functions:

  • A lambda function can take any number of arguments, but they contain only a single expression. An expression is a piece of code executed by the lambda function, which may or may not return any value.
  • Lambda functions can be used to return function objects.
  • Syntactically, lambda functions are restricted to only a single expression.

Let’s understand it more clearly by taking an example which clearly distinguish their features and characteristics, as they give us an appetite for some Python code, functional style.

The identity function, a function that returns its argument, is expressed with a standard Python function definition using the keyword def as follows:

def identity(x):
            return x

Here identity() takes an argument x and returns it upon invocation. In contrast, if we use a Python lambda construction, we get the following:

lambda x : x

In the example above, the expression is composed of:

  • The keyword: lambda
  • A bound variable: x
  • A body: x

The reduction is a lambda calculus strategy which is used to compute the value of the expression. In the next example, it consists of replacing the bound variable x with argument 2:

(lambda x : x+1 ) (2)

This is all how we elaborate the Lambda function in its natural ways, Next In this article, we also found some more interesting things as we will discuss Python’s lambda functions in detail, along with that we learn how to create and also how to use them.

Creating a Lambda Functions:
We use the following syntax to declare a lambda function.

lambda argument(s): expression

As stated above, we can have any number of arguments but only a single expression. The lambda operator cannot have any statements and it returns a function object that we can assign to any variable.

For example:

remainder = lambda num: num % 2 

Output: 1

In this code the lambda num: num % 2 is the lambda function. The num  is the argument while num % 2 is the expression that is evaluated and the result of the expression is returned. The expression gets the modulus of the input parameter by 2. Providing 5 as the parameter, which is divided by 2, we get a remainder of 1.

We should notice here that the lambda function in the above script has not been assigned any name. It simply returns a function object which is assigned to the identifier remainder. However, despite being anonymous, it was possible for us to call it in the same way that we call a normal function.

The statement:

lambda num: num % 2

is similar to the following:

def remainder(num): 
      return num % 2

Here is another example of a lambda function:

product = lambda x, y : x * y 
print(product(2, 3))

Output: 6

The lambda function defined above returns the product of the values of the two arguments.

Use of Lambda Functions:
Lambda functions are used when we need a function for a short period of time. This is commonly used when we want to pass a function as an argument to higher-order functions, that is, functions that take other functions as their arguments.

The use of anonymous function inside another function is explained in the following example:

def testfunc(num): 
      return lambda x : x * num

In the above example, we have a function that takes one argument, and the argument is to be multiplied with a number that is unknown. Let us demonstrate how to use the above function:

def testfunc(num): 
      return lambda x : x * num 
result1 = testfunc(10) 


Here in the above code output should be 90, we use there a lambda function to multiply the number we pass by 10. The same function can be used to multiply the number by 1000:

def testfunc(num): 
      return lambda x : x * num 
result2 = testfunc(1000) 


Similarly the output here should be 9000, It is possible for us to use the testfunc() function to define the above two lambda functions within a single program:

def testfunc(num): 
      return lambda x : x * num 

result1 = testfunc(10) 	
result2 = testfunc(1000) 


Here when we combine the above two programme into a single one then the output is 90 and 9000 respectively. Another way to used lambda function together is by using the built in function in Python such as  as map(  ) and filter( ) etc.

So, In the following section, we will be discussing how to use lambda functions with various Python built-in functions.

The filter ( ) function: The Python’s filter() function takes a lambda function together with a list as the arguments. It has the following syntax:

filter(object, iterable)

The object here should be a lambda function which returns a boolean value. The object will be called for every item in the iterable to do the evaluation. The result is either a True or a False for every item. Note that the function can only take one iterable as the input.

A lambda function, along with the list to be evaluated, is passed to the filter() function. The filter() function returns a list of those elements that return True when evaluated by the lambda funtion. Consider the example given below:

numbers_list = [2, 6, 8, 10, 11, 4, 12, 7, 13, 17, 0, 3, 21] 

filtered_list = list(filter(lambda num: (num > 7), numbers_list)) 


Output is [8, 10, 11, 12, 13, 17, 21]
In the above example, we have created a list named numbers_list with a list of integers. We have created a lambda function to check for the integers that are greater than 7. This lambda function has been passed to the filter() function as the argument and the results from this filtering have been saved into a new list named filtered_list.

The map( ) function:
The map() function is another built-in function that takes a function object and a list. The syntax of the map function is as follows:

map(object, iterable_1, iterable_2, ...)

The iterable to the map() function can be a dictionary, a list, etc. The map() function basically maps every item in the input iterable to the corresponding item in the output iterable, according to the logic defined by the lambda function. Consider the following example:

numbers_list = [2, 6, 8, 10, 11, 4, 12, 7, 13, 17, 0, 3, 21] 

mapped_list = list(map(lambda num: num % 2, numbers_list)) 


And its output is [0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1].
In the script above, we have a list numbers_list, which consists of random numbers. We then call the map() function and pass it a lambda function as the argument. The lambda function calculates the remainder after dividing each number by 2. The result of the mapping is stored in a list named mapped_list. Finally, we print out the contents of the list.

In Python, a lambda function is a single-line function declared with no name, which can have any number of arguments, but it can only have one expression. Such a function is capable of behaving similarly to a regular function declared using Python’s def keyword. Often times a lambda function is passed as an argument to another function.

In this article, we explained the syntax, use-cases, and examples of commonly used lambda functions. If someone has a penchant for mathematics. He/She may have some fun exploring the fascinating world of lambda calculus. Conclusively we can say here that Python lambdas are like salt. A pinch in your spam, ham, and eggs will enhance the flavours, but too much will spoil the dish.

We hope that you liked reading this article. Why don’t you take a look at the top Python projects that you can undertake going forward.

Mayank Mishra