Skip to main content

Command Palette

Search for a command to run...

Python Anonymous Function

Updated
2 min read
B

I am a cloud technology enthusiast

When a function is created with the key word lambda in python its called anonymous function. They don't use the traditional function key word def. Anonymous function (aka lambda) is designed for coding simple functions whereas def used for larger tasks. The name lambda comes from the Lisp programming language. Also don't confuse Python Lambda(anonymous) functions with AWS lambda function as the later is used as serverless compute infrastructure. If you come from C++ background then for the sake of your understanding you can correlate lambdas with C++ inline functions.

Syntax

lambda arg1, arg2,... argn: expression

Example

# Simple sum anonymous function definition
sum = lambda a, b, c: a + b + c;

# Call anonymous sum as a function
print("Sum of a, b, c: ", sum( 3, 4, 5 ))
print("Sum of a, b, c: ", sum( 6, 7, 8 ))

In the above example, function definition sum expects three inputs a, b, c and returns its summation. When calling sum function it appears exactly like any other python function created using def with few caveats.

  • Lambdas are basically single body expressions and not true function with a statement block. They don't contain any explicit return statement rather whatever expression mentioned in lambda is computed and the value returned at the end.

  • Just like def they can take multiple arguments but return just one value.

  • Lambda functions creates local scope and cannot access variables other than those in their parameter list and those in the global namespace.

Just like def lambda can have default values.


sum = lambda a=3, b=2, c=1 : a + b + c;

print("Sum of a, b, c: ", sum( 7, 9, 11 ))    # prints 27

We can use lambda to generate multiplier function.

def multiplier(n):
  return lambda a : a * n

doubler = multiplier(2)
print(doubler(5))        # prints 10

tripler = multiplier(3)
print(tripler(5))        # prints 15

We can create jump tables.

L = [lambda x: x ** 2, lambda x: x ** 3, lambda x: x ** 4] 

for f in L:
    print(f(2))    # Prints 4, 8, 16

print(L[0](3))     # Prints 9