python logo


Tag: reduce

python lambda if

We can create anonymous functions, known as lambda functions. Lambda functions are different from normal Python functions, they originate from Lambda Calculus. It allows you to write very short functions.

Related Course:
Python Programming Bootcamp: Go from zero to hero

Lambda function example
This code shows the use of a lambda function:

#!/usr/bin/env python

f = lambda x : 2 * x
print f(3)

A return statements is never used in a lambda function, it always returns
something. A lambda functions may contain if statements:

#!/usr/bin/env python

f = lambda x: x > 10
print(f(2))
print(f(12))

map function


The definition of map is map(function,iterable). It applies a function to every item in the iteratable. We can use map() on a lambda function with a list:

#!/usr/bin/env python

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

Anywhere you use lambda functions, you could use normal functions instead. A lambda function is not a statement, it is an expression. Lambda functions do not support a block of statements.

filter function


filter(function,iterable) creates a new list from the elements for which the function returns True. Example:

#!/usr/bin/env python

list = [1,2,3,4,5,6,7,8,9,10]
newList = filter(lambda x: x % 2 == 0, list)
print(newList)

The returning list returns contains only the elements for which the lambda expression “lamba x: x % 2 == 0” is true.

reduce function


The reduce function, reduce(function, iterable) applies two arguments cumulatively to the items of iterable, from left to right. Example:

#!/usr/bin/env python

list = [1,2,3,4,5]
s = reduce(lambda x,y: x+y, list)
print(s)

In this case the expression is always true, thus it simply sums up the elements of the list. Another example:

#!/usr/bin/env python

list = [10,6,7,5,2,1,8,5]
s = reduce(lambda x,y: x if (x > y) else y, list)
print(s)


Related Course:
Python Programming Bootcamp: Go from zero to hero