A guide to Python Lambda functions, with examples

This article introduces Python lambda functions and how to write and use them.

Although Python is an object-oriented programming language, lambda functions come in handy when doing different kinds of functional programming.

Note: This article assumes that you already understand Python programming and how to use a standard function. It is also assumed that Python 3.8 or higher is installed on your device.

Explain Python Lambda functions

In Python, functions can take one or more positional or keyword arguments, variable list of arguments, variable list of keyword arguments, etc. They can be passed to a higher order function and returned as an output. Regular functions can have multiple expressions and multiple statements. They also always have a name.

a python lambda function is just an anonymous function. You could also call it a nameless function. Normal Python functions are defined by the def keyword. Lambda functions in Python are usually composed of the lambda keyword, any number of arguments, and an expression.

Note: the terms lambda functions, lambda expressionsand lambda shapes can be used interchangeably, depending on the programming language or the programmer.

Lambda functions are mostly used as a single line. They are very often used in higher order functions such as map() and filter(). This is because anonymous functions are passed as arguments to higher-order functions, which is not the case only in Python programming.

A lambda function is also very useful for handling list comprehension in Python – with various options for using Python lambda expressions for this purpose.

Lambdas are great when used for conditional rendering in UI frameworks like Tkinter, wxPython, Kivy, etc. Although the operation of Python GUI frameworks is not covered in this article, some code snippets reveal heavy use of lambda functions in user interaction.

Things to understand before diving into Python Lambda functions

Because Python is an object-oriented programming language, everything is an object. Python classes, class instances, modules, and functions are all treated as objects.

A function object can be assigned to a variable.

It is not uncommon to assign variables to regular functions in Python. This behavior can also be applied to lambda functions. This is because they are functional objects, even if they have no name:

def greet(name):
    return f'Hello {name}'

greetings = greet
greetings('Clint')
>>>>
Hello Clint

Higher order functions such as map(), filter() and reduce()

It’s likely that you need to use a lambda function in built-in functions like filter() and map()and also with reduce() — which is imported from the functools module in Python, as it is not a built-in function. By default, higher order functions are functions that take other functions as arguments.

As seen in the code samples below, normal functions can be replaced with lambdas, passed as arguments in one of these higher-order functions:


names = ['Clint', 'Lisa', 'Asake', 'Ada']

greet_all = list(map(greet, names))
print(greet_all)
>>>>
['Hello Clint', 'Hello Lisa', 'Hello Asake', 'Hello Ada']

numbers = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
def multiples_of_three(x):
        return x % 3 == 0

print(list(filter(multiples_of_three, numbers)))
>>>>
[12, 15, 18]

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def add_numbers(x, y):
        return x * y

print(reduce(add_numbers, numbers))
>>>>
55

The difference between a statement and an expression

A common point of confusion among developers is to differentiate between a statement and an expression in programming.

A statement is any piece of code that does something or performs an action – like if Where while conditions.

A expression is made up of a combination of variables, values, and operators and evaluates to a new value.

This distinction is important as we explore the topic of lambda functions in Python. An expression like the one below returns a value:

square_of_three = 3 ** 2
print(square_of_three)
>>>>
9

A statement looks like this:

for i in range(len(numbers), 0, -1):
        if i % 2 == 1:
                print(i)
        else:
                print('even')
>>>>
even 9 even 7 even 5 even 3 even 1

How to Use Python Lambda Functions

The Python style guide states that every lambda function should start with the keyword lambda (unlike normal functions, which start with the def keyword). The syntax of a lambda function usually looks like this:

lambda arguments : expression

Lambda functions can take any number of positional arguments, keyword arguments, or both, followed by a colon and a single expression. There cannot be more than one expression, as it is syntactically restricted. Let’s look at an example lambda expression below:

add_number = lambda x, y : x + y
print(add_number(10, 4))
>>>>
14

In the example above, the lambda expression is assigned to the variable add_number. A function call is made by passing arguments, resulting in 14.

Let’s take another example below:

discounted_price = lambda price, discount = 0.1, vat = 0.02 : price * (1 - discount) * (1 + vat)

print(discounted_price(1000, vat=0.04, discount=0.3))
>>>>
728.0

As seen above, the lambda function evaluates to 728.0. A combination of positional arguments and keywords are used in the Python lambda function. When using positional arguments, we cannot change the order shown in the function definition. However, we can place keyword arguments at any position only after the positional arguments.

Lambda functions are always executed as Immediately Invoked Function Expressions (IIFE) in JavaScript. This is primarily used with a Python interpreter, as shown in the following example:

print((lambda x, y: x - y)(45, 18))
>>>>
27

The object of the lambda function is surrounded by parentheses, and another pair of parentheses follows closely with the arguments passed. As an IIFE, the expression is evaluated and the function returns a value assigned to the variable.

Python lambda functions can also be executed in a list comprehension. A list comprehension always has an output expression, which is replaced by a lambda function. Here are some examples:

my_list = [(lambda x: x * 2)(x) for x in range(10) if x % 2 == 0]
print(my_list)
>>>>
[0, 4, 8, 12, 16]
value = [(lambda x: x % 2 and 'odd' or 'even')(x) for x in my_list] 
print(value)
>>>>
['even', 'even', 'even', 'even', 'even']

Lambda functions can be used when writing ternary expressions in Python. A ternary expression produces a result based on a given condition. Check out the examples below:

test_condition1 = lambda x: x / 5 if x > 10 else x + 5
print(test_condition1(9))
>>>>
14
test_condition2 = lambda x: f'{x} is even' if x % 2 == 0 else (lambda x: f'{x} is odd')(x)

print(test_condition2(9))
>>>>
9 is odd

Lambda functions in higher order functions

The concept of higher-order functions is popular in Python, as it is in other languages. These are functions that accept other functions as arguments and also return functions as output.

In Python, a higher-order function takes two arguments: a function and an iterable. The function argument is applied to each element of the iterable object. Since we can pass a function as an argument to a higher-order function, we can also pass a lambda function.

Here are some examples of a lambda function used with the map() function:

square_of_numbers = list(map(lambda x: x ** 2, range(10)))

print(square_of_numbers)
>>>>
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
strings = ['Nigeria', 'Ghana', 'Niger', 'Kenya', 'Ethiopia', 'South Africa', 'Tanzania', 'Egypt', 'Morocco', 'Uganda']

length_of_strings = list(map(lambda x: len(x), strings))

print(length_of_strings)
>>>>
[7, 5, 5, 5, 8, 12, 8, 5, 7, 6]

Here are some lambda functions used with the filter() function:

length_of_strings_above_five = list(filter(lambda x: len(x) > 5, strings))

print(length_of_strings_above_five)
>>>>
['Nigeria', 'Ethiopia', 'South Africa', 'Tanzania', 'Morocco', 'Uganda']
fruits_numbers_alphanumerics = ['apple', '123', 'python3', '4567', 'mango', 'orange', 'web3', 'banana', '890']

fruits = list(filter(lambda x: x.isalpha(), fruits_numbers_alphanumerics))

numbers = list(filter(lambda x: x.isnumeric(), fruits_numbers_alphanumerics))

print(fruits)
print(numbers)
>>>>
['apple', 'mango', 'orange', 'banana']
['123', '4567', '890']

Here are some lambda functions used with the reduce() function:

values = [13, 6, 12, 23, 15, 31, 16, 21]
max_value = reduce(lambda x,y: x if (x > y) else y, values)
print(max_value)
>>>>
31
nums = [1, 2, 3, 4, 5, 6]
multiplication_of_nums = reduce(lambda x,y: x*y, nums)

print(multiplication_of_nums)
>>>>
720

Conclusion

Although Python lambdas can significantly reduce the number of lines of code you write, they should be used sparingly and only when necessary. Readability of your code should be prioritized over conciseness. For more readable code, always use a normal function when suitable for lambda functions, as recommended by the Python Style Guide.

Lambdas can be very handy with Python ternary expressions, but again, try not to sacrifice readability. Lambda functions come into their own when higher order functions are used.

In summary:

  • Python lambdas are good for writing one-line functions.
  • They are also used for IIFEs (Immediately Invoked Function Expression).
  • Lambdas should not be used when there are multiple expressions, as this makes the code unreadable.
  • Python is an object-oriented programming language, but lambdas are a good way to explore functional programming in Python.

Related Content:

Comments are closed.