The function without a name is called the Anonymous function in Python. Normally functions are defined using the
def keyword in Python but anonymous functions are defined using the
lambda arguments : expression
It’s also called the lambda function because it is defined with the lambda keyword.
Python Anonymous function examples
A simple example created a function to return the sum of two arguments using Anonymous Functions in Python.
def sum_fun(a, b): return a + b print(sum_fun(1, 2))
The anonymous function
Converts the above code to an anonymous/lambda function.
sum = lambda a, b: (a + b) print(sum(1, 2))
Why Use Anonymous Functions?
Answer: Use it when we require a nameless function for a short period of time. Anonymous functions are used along with built-in functions like
map() etc. Use an anonymous function inside another function.
def myfunc(n): return lambda a : a * n
Example use with filter()
The function to filter out only even numbers from a list.
my_list = [1, 5, 4, 6, 8, 10, 11, 12] res = list(filter(lambda x: (x % 2 == 0), my_list)) print(res)
Output: [4, 6, 8, 10, 12]
Example use with map()
function to double all the items in a list.
my_list = [0, 2, 4, 6, 8, 10] res = list(map(lambda x: x * 2, my_list)) print(res)
Output: [0, 4, 8, 12, 16, 20]
Do comment if you have any doubts or suggestions on this Python function code.
Note: IDE: PyCharm 2021.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.