Lambda | Map | filter | Reduce | Python tutorial

Lambda

Creating a function normally (using def) assigns it to a variable automatically.
This is different from the creation of other objects – such as strings and integers – which can be created on the fly, without assigning them to a variable.

The same is possible with functions, provided that they are created using lambda syntax.
Functions created this way are known as anonymous.

This approach is most commonly used when passing a simple function as an argument to another function. The syntax is shown in the next example and consists of the lambda keyword followed by a list of arguments, a colon, and the expression to evaluate and return.

Lambda functions get their name from lambda calculus, which is a model of computation invented by Alonzo Church.

Lambdas limitations

Lambda functions aren’t as powerful as named functions.
They can only do things that require a single expressionusually equivalent to a single line of code.

In the code above, we created an anonymous function on the fly and called it with an argument.

question: Fill in the blanks to create a lambda function that returns the square of its argument, and call it for the number 8.

a = ( lambda x: x*x) (8)
OR
a = lambda x: x*x
a(8)

Lambda functions can be assigned to variables, and used like normal functions.

What is the result of this code?
triple = lambda x: x * 3
add = lambda x, y: x + y
print(add(triple(3), 4))
o/p: 13

MAP

The built-in functions map and filter are very useful higher-order functions that operate on lists (or similar objects called iterables).

The function map takes a function and an iterable [list, tuple, string defincation of iterable An iterable is any Python object capable of returning its members one at a time, permitting it to be iterated over in a for-loop]as arguments, and returns a new iterable with the function applied to each argument.

We could have achieved the same result more easily by using lambda syntax.

To convert the result into a list, we used list explicitly.

exercise: Give a list multiply each item in the list by 2 using lambda syntax.

nums = [2,6,12]
a = list(map(lambda x:x*2), nums)

filter

The function filter filters an iterable by removing items that don’t match a predicate (a function that returns a Boolean).
Example:

Like map, the result has to be explicitly converted to a list if you want to print it.

exercise: Given a list extract all the item less than 5
nums = [2,6,12,1,4]
a = list(filter(lambda x:x<2), nums)

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Design a site like this with WordPress.com
Get started