Lambda functions

There are a bunch of lambda functions that can be used on lists. They are specifically important in the context of algorithms and provide the ability to create a function on the fly. Sometimes, in the literature, they are also called anonymous functions. This section demonstrates their uses:

  • Filtering data: To filter the data, first, we define a predicate, which is a function that inputs a single argument and returns a Boolean value. The following code demonstrates its use:
>>> list(filter(lambda x: x > 100, [-5, 200, 300, -10, 10, 1000]))
[200, 300, 1000]

Note that, in this code, we filter a list using the lambda function, which specifies the filtering criteria. The filter function is designed to filter elements out of a sequence based on a defined criterion. The filter function in Python is usually used with lambda. In addition to lists, it can be used to filter elements from tuples or sets. For the preceding code, the defined criterion is x > 100. The code will iterate through all the elements of the list and will filter out the elements that do not pass this criterion. 

  • Data transformation: The map() function can be used for data transformation using a lambda function. An example is as follows:
>>> list(map(lambda x: x ** 2, [11, 22, 33, 44,55]))
[121, 484, 1089, 1936, 3025]

Using the map function with a lambda function provides quite powerful functionality. When used with the map function, the lambda function can be used to specify a transformer that transforms each element of the given sequence. In the preceding code, the transformer is multiplication by two. So, we are using the map function to multiply each element in the list by two.

  • Data aggregation: For data aggregation, the reduce() function can be used, which recursively runs a function to pairs of values on each element of the list: 
from functools import reduce
def doSum(x1,x2):
return x1+x2
x = reduce(doSum, [100, 122, 33, 4, 5, 6])

Note that the reduce function needs a data aggregation function to be defined. That data aggregation function in the preceding code is functools. It defines how it will aggregate the items of the given list. The aggregation will start from the first two elements and the result will replace the first two elements. This process of reduction is repeated until we reach the end, resulting in one aggregated number. x1 and x2 in the doSum function represent two numbers in each of these iterations and doSum represents the aggregation criterion for them.

The preceding code block results in a single value (which is 270).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.114.125