Python Anonymous function | Function defined with no names

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 keyword.


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.

Normal function

def sum_fun(a, b):
    return a + b

print(sum_fun(1, 2))

Output: 3

The anonymous function

Converts the above code to an anonymous/lambda function.

sum = lambda a, b: (a + b)

print(sum(1, 2))


Python Anonymous function

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 filter(), map() etc. Use 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))


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))


Output: [0, 4, 8, 12, 16, 20]

Do comment if you have any doubts and suggestions on this Python function code.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.