Tag: filter
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 |
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 |
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 |
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 |
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 |
In this case the expression is always true, thus it simply sums up the elements of the list. Another example:
#!/usr/bin/env python |
Related Course:
Python Programming Bootcamp: Go from zero to hero