Python Lambda Functions, Explained

Learn the syntax and uses of the lambda function, which is an alternative to the regular Python function.



Python Lambda Functions, Explained
Image by Editor

 

Since the advent of computer programming, functions have played a key role by offering advantages such as reusability, readability, modularity, error reduction, and easy modification. Reusability is considered one of the most useful traits of a function but what if I tell you there are functions that are not reusable but still useful? To find out, read along!

 

Lambda Functions and their Syntax

 

A lambda function does not have a name and is an immediately invoked function. It can accept any number of arguments but returns only one expression, unlike regular functions.

It has the following syntax:

lambda parameters: expression

 

The syntax of the lambda function, as shown above, has three elements:

  • The keyword “lambda” — it is analogous to ‘def’ in user-defined functions
  • parameters — analogous to arguments in normal functions
  • expression — it is the operation that gets evaluated to arrive at the result

Unlike regular functions, the parameters are not surrounded by parentheses in lambda functions. Considering that the expression is a one-liner, it needs to be short but at the same time must perform the required operations over the parameters. A lambda function is consumed at the definition and thus cannot be reused without explicitly defining again.

Generally, a lambda function is passed as an argument to a higher-order function such as Python built-in functions – filter(), map(), or reduce(). But what is a higher-order function? 

A higher-order function is defined as a function that takes in other functions as arguments (discussed in subsequent sections).

 

Uses and Examples

 

Now that we are acquainted with the syntax, it’s time to understand the lambda functions with a simple example. Let’s say you want to find the square of a number. You can either define a function “square” or write a lambda function as shown below:

def square(x):
    return x**2

 

lambda x: x**2

 

The lambda function above accepts a single argument x and returns its square.

 

Calling a Lambda Function

 

Calling a lambda function is as simple as wrapping the construction of the lambda function first, followed by the argument in the parentheses.

(lambda x: x**2)(3)

 

Output >> 9

 

Calling With Multiple Arguments

 

For a lambda function with multiple arguments, the input parameters are separated by a comma. The corresponding arguments follow the same order at the time of execution.

(lambda x, y, z: x**2 + y**2 + z**2)(1, 2, 0)

 

Output >> 100

 

Single Conditional Statement

 

You can also perform conditional operations such as if-else block as shown the below example: 

(lambda x: 100 if x > 100 else (50 if x > 50 else x))(75)

 

Output >> 100

 

Nested Conditional Statement

 

Because these are one-liner functions, conditional nesting is performed with the help of round braces rather than indentation.

(lambda x: 100 if x > 100 else (50 if x > 50 else x))(75)

 

Output >> 50

 

The user-defined function corresponding to the above lambda function looks like below.

def conditional_statement_demo(x):
    if x > 100:
        return100
    elif x > 50:
        return 50
    else:
        return x
conditional_statement_demo(75)

 

Output >> 50

 

Note that user-defined functions are a better choice in a nested condition scenario.

 

Assigning to a Variable

 

A lambda function can also be assigned to a variable and called like a user-defined function.

square = lambda x: x**2
square(3)

 

Output >> 9

 

Even though it is possible to assign the function to a variable, it is sparingly used as it defeats the sole purpose of a lambda function i.e. immediate invocation. Variable assignment is rather useful when using lambda function inside another function.

 

String Concatenation

 

Thw following example shows how to concatenate the two strings – where you print a welcome message with the person’s name that is passed as an argument.

welcome_msg = lambda name : print('Hi', name + '! This is your computer.')
welcome_msg(“Vidhi”)

 

Output >> Hi Vidhi! This is your computer.

 

Nested Function

 

The Lambda function is most powerful when used inside another function.

Let’s consider an example of a user-defined function that takes a single argument which is used as an exponent of any number.

def power(y):
  return lambda x : x**y
square = power(2)
print(square(5))

 

Output >> 25

 

Calling by an Underscore

 

Time for some magic! Let’s us go through another way to call a lambda function.

lambda x, y : x**y
_(2,3)

 

Output >> 8

 

What just happened here? Once you define the lambda function which is essentially an anonymous function, it is called using an “_” and the arguments.

 

Using with map()

 

Lambda functions are used quite often as a map() functions argument. It maps a sequence to a function and doesn’t require explicit definition (especially for trivial operation like the one shown below)

print(list(map(lambda x: x**2, range(1,11))))

 

Output >> [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

 

The map() maps the sequence from 1 to 10 to the lambda function and returns the square of all the elements of the sequence. 

 

Using with reduce()

 

A reduce function operates on all the elements of the sequence with the operation defined in the lambda function to return a single output value. The example multiplies all the elements of the sequence from 1 to 4 and computes the output as 1*2*3*4 = 24. 

from functools import reduce
print(reduce((lambda x, y: x * y), range(1,5)))

 

Output >> 24

 

Lets examine another example where reduce is used with a lambda function to return the greater of the two elements. When a list is passed as the second argument, it returns the largest number from the list.

lst = [8, 9, 50, 6, 12]
print(reduce(lambda a, b: a if a > b else b, lst))

 

Output >> 50

 

Using with filter()

 

Another great use of lambda functions is with filter(). The lambda function returns True if the number is odd in the following example. When used with the filter, it returns all odd numbers in the list.

lst = [12, 2, 8, 46, 3, 34, 68, 92, 49]
result = list(filter(lambda x: (x % 2 != 0), lst))
print(result)

 

Output >> [3, 49]

 

Lambda functions are very handy and save a lot of coding effort. The post explained the syntax of the lambda function and how it is different from a user-defined function. Hope you found it useful to get started with the basics of lambda functions.

 
 
Vidhi Chugh is an AI strategist and a digital transformation leader working at the intersection of product, sciences, and engineering to build scalable machine learning systems. She is an award-winning innovation leader, an author, and an international speaker. She is on a mission to democratize machine learning and break the jargon for everyone to be a part of this transformation.