This text introduces Python lambda functions and the way write and use them.

Although Python is an object-oriented programming language, lambda functions are handy once you’re doing various sorts of functional programming.

Note: this text will assume you already understand Python programming and find out how to use a daily function. It’s also assumed you’ve Python 3.8 or above installed in your device.

Explaining Python Lambda Functions

In Python, functions can soak up a number of positional or keyword arguments, a variable list of arguments, a variable list of keyword arguments, and so forth. They will be passed right into a higher-order function and returned as output. Regular functions can have several expressions and multiple statements. Additionally they at all times have a reputation.

A Python lambda function is solely an anonymous function. It is also called a nameless function. Normal Python functions are defined by the def keyword. Lambda functions in Python are frequently composed of the lambda keyword, any variety of arguments, and one expression.

Note: the terms lambda functions, lambda expressions, and lambda forms will be used interchangeably, depending on the programming language or programmer.

Lambda functions are mostly used as one-liners. They’re used fairly often inside higher-order functions like map() and filter(). It is because anonymous functions are passed as arguments to higher-order functions, which isn’t only done in Python programming.

A lambda function can also be 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 rending in UI frameworks like Tkinter, wxPython, Kivy, etc. Although the workings of Python GUI frameworks aren’t covered in this text, some code snippets reveal heavy use of lambda functions to render UI based on a user’s interaction.

Things to Understand before Delving into Python Lambda Functions

Because Python is an object-oriented programming language, every little thing is an object. Python classes, class instances, modules and functions are all handled as objects.

A function object will be assigned to a variable.

It’s not unusual to assign variables to regular functions in Python. This behavior can be applied to lambda functions. It is because they’re function objects, although they’re nameless:

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

greetings = greet
greetings(‘Clint’)
>>>>
Hello Clint

Higher-order functions like map(), filter(), and reduce()

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

As seen within the code examples below, the conventional functions will be replaced with lambdas, passed as arguments into any of those 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 an announcement and an expression

A typical point of confusion amongst developers is differentiating between an announcement and an expression in programming.

A statement is any piece of code that does something or performs an motion — resembling if or while conditions.

An expression is product of a mixture of variables, values, and operators and evaluates to a recent value.

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

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

An announcement 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

Easy methods to Use Python Lambda Functions

The Python style guide stipulates that each lambda function must begin with the keyword lambda (unlike normal functions, which begin with the def keyword). The syntax for a lambda function generally goes like this:

lambda arguments : expression

Lambda functions can take any variety of positional arguments, keyword arguments, or each, followed by a colon and just one expression. There can’t be a couple of expression, because it’s syntactically restricted. Let’s examine an example of a lambda expression below:

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

From the instance above, the lambda expression is assigned to the variable add_number. A function call is made by passing arguments, which evaluates to 14.

Let’s take one other 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 mix of positional and keyword arguments are utilized in the Python lambda function. While using positional arguments, we will’t alter the order outlined within the function definition. Nevertheless, we will place keyword arguments at any position only after the positional arguments.

Lambda functions are at all times executed identical to immediately invoked function expressions (IIFEs) in JavaScript. This is generally used with a Python interpreter, as shown in the next example:

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

The lambda function object is wrapped inside parentheses, and one other pair of parentheses follows closely with arguments passed. As an IIFE, the expression is evaluated and the function returns a worth that’s assigned to the variable.

Python lambda functions can be executed inside a listing comprehension. An inventory comprehension at all times has an output expression, which is replaced by a lambda function. Listed below 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 will be used when writing ternary expressions in Python. A ternary expression outputs a result based on a given condition. Take a look at 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 inside higher-order functions

The concept of higher-order functions is popular in Python, just as in other languages. They’re functions that accept other functions as arguments and in addition return functions as output.

In Python, a higher-order function takes two arguments: a function, and an iterable. The function argument is applied to every item within the iterable object. Since we will pass a function as an argument to a higher-order function, we will equally pass in a lambda function.

Listed below 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]

Listed below 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’]

Listed below 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 variety of lines of code you write, they must be used sparingly and only when mandatory. The readability of your code must be prioritized over conciseness. For more readable code, at all times use a traditional function where suited over lambda functions, as advisable by the Python Style Guide.

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

In summary:

  • Python lambdas are good for writing one-liner functions.
  • Also they are used for IIFEs (immediately invoked function expression).
  • Lambdas shouldn’t be used when there are multiple expressions, because it makes code unreadable.
  • Python is an object-oriented programming language, but lambdas are a great approach to explore functional programming in Python.

Related content: