Cool Functions
Lambda Function💡¶
Lambda Functions
A lambda function is a small anonymous (nameless) function defined using the keyword lambda
. It can take any number of arguments, but can only have one expression, which is implicitly returned. They are often used for small, single-operation tasks, especially when passed as arguments to higher-order functions.
The expression is evaluated and returned.
Output | |
---|---|
Higher Order Function ⬆️¶
Higher Order Function
A Higher Order Function (HOF) is a function that either takes one or more functions as arguments or returns a function as its result. map
, filter
, and reduce
are common HOFs.
This custom function demonstrates a basic higher-order function that takes another function (func
) and a list (arg_list
) as input.
Output | |
---|---|
Map¶
The map()
function applies a given function to all items in an input list (or other iterable) and returns a map object (which can be converted to a list).
Syntax: map(function, iterable)
Mapping Examples
Output | |
---|---|
Output | |
---|---|
Output | |
---|---|
Filter¶
The filter()
function constructs an iterator from elements of an iterable for which a function returns true.
Syntax: filter(function, iterable)
Filtering Examples
Reduce¶
The reduce()
function applies a function cumulatively to the items of an iterable, reducing the iterable to a single value. It is located in the functools
module.
Syntax: functools.reduce(function, iterable)
Reduce Examples
Accumulates the sum: ( ( (1+2)+3 )+4 )+5
Output | |
---|---|
The lambda function returns the greater of the two values being compared at each step, accumulating the maximum value.
Output | |
---|---|