Python Anonymous (Lambda) Function
Python Anonymous (Lambda) Function, means a function without a name.
As we have already discussed that, to define a function in Python we use the
def keyword, but to define
an anonymous (lambda) function we use the keyword,
That’s why the anonymous function is also called lambda function.
lambda arguments: expression
Few Points to Remember:
Lambda function can have any number of arguments, but only one expression.
The expression will be evaluated and return.
Lambda function cab be use anywhere, where the function object is required.
Lambda function to square a number
square = lambda x : x * x print(square(4)) print(square(5))OUTPUT
In the above program,
lambda x : x * x is lambda function,
x is argument and
x * x is expression.
square is a function pointer which points to the lambda function, and can use to call the lambda function.
The lambda function
square = lambda x : x * x
is similar to
def square(x): return x * xOUTPUT
Hello from myfun I accept one argument arg1 : Hello
Use of Lambda Function:
Many built-in functions are available which takes argument as function( those are called higher order functions ), like
reduce() etc.. in that case lambda function has the best use.
Use with filter()
filter() function takes first argument as function and second argument as a sequence(like list).
The argument function will be called on every item of the sequence and return a new list, which contains items for which
the function is evaluated to
Example to filter only even numbers from a list
li = [1,2,5,12,16,8,10] new_li = list(filter(lambda x: (x%2 == 0) , li)) print(new_li)OUTPUT
Use with map()
map() function takes first argument as function and second argument as list.
The argument function will be called on every item of the list and return a new list, which contains items for which the function is evaluated.
Example to double all the numbers of a list
li = [1,2,5,12,16] new_li = list(filter(lambda x: x * 2 , li)) print(new_li)OUTPUT
[1, 4, 10, 24, 32]
Next chapter is Anonymous Function
Training For College Campus
We offers college campus training for all streams like CS, IT, ECE, Mechanical, Civil etc. on different technologies
C, C++, Data Structure, Core Java, Advance Java, Struts Framework, Hibernate, Python, Android, Big-Data, Ebedded & Robotics etc.
Please mail your requirement at firstname.lastname@example.org
Projects For Students
Students can contact us for their projects on different technologies Core Java, Advance Java, Android etc.
Students can mail requirement at email@example.com