Python

How to Use Lambda Functions in Python

This article will explain how to use Lambda functions in Python. Lambda functions can be used to write concise one-liners, implement logic and quickly get return values that can be fed to other expressions.

About Lambda Functions

Lambda functions in python are unnamed and anonymous functions that can be used to create expressions that return some kind of value based on the calculations implemented in the expression itself. Logic in these lambda functions can be written in a concise way, usually something that fits easily in one line. Sometimes they can be difficult to read, especially if people are not well versed with Lambda functions. However they do have the benefit of keeping things together within code blocks and they help better in understanding the context.

Syntax of Lambda Functions

The syntax of a Lambda function in Python Looks like this:

multiply = lambda x, y: x * y

The first part of the lambda expression, just before colon (:) symbol, takes parameters as arguments. The second part, after the colon symbol, needs to be a return value. This return value can be an expression with logic as well. In fact, Lambda functions are used almost all the time to implement some logic on supplied arguments and then return the final result.

To test the Lambda function stated above, you can use the following statement:

print (multiply(3, 4))

You should get the following output:

12

The same lambda function would be otherwise written in the following way:

def multiply (x, y):
    return x * y

print (multiply(3, 4))

Both code samples will give the same output. Some more examples of Lambda functions are explained below.

Pass Lambda Functions as Arguments

You can use Lambda functions to do calculations and supply the return value as arguments to other functions. Sort method in Python takes a “key” argument where you can specify a callable function that takes a single argument for sorting purposes. Instead of first defining a separate function that returns a key and then supplying the function’s reference to the argument, you can simply use a Lambda function.

fruits = [(2, 'apples'), (4, 'oranges'), (3, 'bananas')]
fruits.sort(key=lambda element: element[0])
print (fruits)

The code above will produce the following output:

[(2, 'apples'), (3, 'bananas'), (4, 'oranges')]

You can use lambda in any such method that takes a callable function as argument (filter method for instance).

Use Lambda Functions in List Comprehensions

You can use Lambda in list comprehensions and a list will be duly created from the values returned by the Lambda expression.

get_square = lambda a: a * a
squares = [get_square(x) for x in range(5)]
print (squares)

This will produce the following output:

[0, 1, 4, 9, 16]

The code sample above can also be written in the following way where “x” is supplied to the lambda function as a argument:

squares = [(lambda x: x * x)(x) for x in range(5)]
print (squares)

This example just illustrates use of Lambda functions in list comprehensions. You can otherwise easily calculate squares using a minimal list comprehension statement:

print ([x * x for x in range(5)])

Use Lambda Functions in Python Dictionaries

The code sample below illustrates Lambda functions used within key-value pairs in a Python dictionary. Once defined, you can call these functions any time.

calculate = {'sum' : lambda a, b: a + b, 'difference': lambda a, b: a - b}
print (calculate['sum'](4, 5))
print (calculate['difference'](4, 5))

You should get the following output after running the above code:

9
-1

Conclusion

Lambda functions provide an excellent way to write shorthand expressions and keep things neat and organized without unnecessary creating a lot of named functions. However, overusing Lambda functions can make code difficult to read especially when code is being looked upon by more than one person. It is better to have more readable code (even if it is verbose) than having something that may be a bit hard to understand on revisits.

About the author

Nitesh Kumar

Nitesh Kumar

I am a freelancer software developer and content writer who loves Linux, open source software and the free software community.