How are lambdas useful?

Lambdas, also known as anonymous functions, are useful in Python because they allow you to create small, one-time use functions without having to define them with a full function statement. This can make your code more readable and simplify certain operations. Here is an example of a lambda function being used to square a number:

squared = lambda x: x**2
print(squared(5))  # prints 25

In this example, the lambda function takes in one argument, x, and returns the result of x squared. The function is assigned to the variable squared, which can then be called like any other function.

Watch a course Python - The Practical Guide

Another common use case for lambda functions is when they are passed as arguments to higher-order functions such as map, filter, and reduce.

nums = [1,2,3,4,5]
squared_nums = map(lambda x: x**2, nums)
print(list(squared_nums)) # prints [1, 4, 9, 16, 25]

In this example, the lambda function is passed to the map function and is used to square each element in the nums list. The map function returns an iterator, which is then passed to list() to return a list of squared numbers.