Primer to Python Lambda Function
Modified: August 15, 2024
Published: August 18, 2016
Tags:
Lambda function is a way to create small anonymous functions, i.e. functions without a name. These functions are throw-away functions, i.e. they are just needed where they have been created.
The general syntax of a lambda function is quite simple:
lambda argument_list: expression
Sample
|
|
Lambda functions are mainly used in combination with the functions filter(), map() and reduce()
- map: Apply function to all elements in sequence
- filter: Apply function to all elements in sequence and return only those elements for which the function returns True
- reduce: Apply function to all elements in sequence cumulatively
Map
The function map(f,l) applies the function f() to all the elements of the sequence l. It returns a new list with the elements changed by f().
Without lambda:
|
|
With lambda
|
|
Filter
The function filter(f,l) needs a function f as its first argument. f returns a Boolean value, i.e. either True or False.
Here the function will list the odd Fibonacci numbers
|
|
Reduce
The function reduce(f,l) continually applies the function f() to the sequence l. It returns a single value.
- At first the first two elements of sequence are applied to f, i.e. f(s1,s2)
- Next f() is applied on the previous result and the third element of the list, i.e. f(f(s1,s2),s3)
- The process continues till the last element of the sequence.
|
|
Reference:
It will help me to improve/learn.