Anonymous Functions in Python




In this post, we are going to see Anonymous functions in Python.

What are Anonymous functions?

  • A function without a name is called as Anonymous or lambda functions.
  • An anonymous function is created using the lambda keyword

Syntax

lambda args: expression

Why we need Anonymous functions?

  • Anonymous functions are generally used when the function is required for a short time.
  • These are passed as arguments for other higher-order functions

Example


# program to illustrate Anonymous functions

square = lambda x : x**2

print(square(5))

check output here

This is almost identical to


def square (n):
  return n**2

print(square(5))

check output here

Usage with filter()

The filter() function takes 2 params, one is a function & the other is a list.


# Program to illustrate the usage of Anonymous functions with filter()

a = [1,2,3,4,5,6]

b = list(filter(lambda x: x%2 != 0, a))

print(b)

check output here