Functional Programming in Python with Lambda Map Reduce and Filter

functional programming in python

Functional programming in Python is possible with the use of lambda map reduce and filter functions. This article briefly describe use of each these functions.

Lambda : Lambda specifies an anonymous function. It is used to declare a function with no name; When you want to use function only once. But why would you declare a function if you don’t want to reuse the code? Read on you’ll see.

Syntax: lambda arg1, arg2 : expression

lambda x : x*x

This lambda expression with just one argument x which returns square of x.

Map : It takes two arguments, the first argument is name of a function and second argument is a sequence. map() applies function f to all elements in the sequence and returns a new sequence.

Syntax: map (func, sequence)

list = [1, 2, 3]
map (lambda x : x*x, list)
[1, 4, 9]

This code also demonstrates use of lambda. Instead writing a square function we substituted it with a lambda expression. map() applies it to all elements in the list and returns a new list with each element square of original element.

Reduce: reduce() continuously applies a function to a sequence and returns one value. In the following example we sum all elements in the original list.

Syntax: reduce (func, sequence)

reduce (lambda x,y : x+y, list)
6

Filter: It filters all values in a sequence for which given function returns True.

Syntax: filter (booleanFunc, sequence)

filter (lambda x : x%2, list)
[1, 3]

Above example returns all odd integers in the list. Remember 2%2=0 is treated as boolean value False.

Comments

avatar
  Subscribe  
Notify of