Python Anonymous Function (Lambda Function)

In this python tutorial, we will discuss what is Python Anonymous function, What is Lambda function in python. Also, We will see these below topics as:

  • Anonymous function with lambda in Python
  • Anonymous function without lambda
  • Anonymous function multiple lines in Python
  • Anonymous function as an argument in Python
  • Anonymous function without argument
  • Anonymous function examples in Python
  • python anonymous function callback
  • Anonymous function multiple arguments
  • Anonymous function in a Python dictionary
  • Python anonymous function as a parameter
  • Anonymous function map in Python
  • Python lambda function without if-else
  • Python lambda function with filter
  • Python lambda function with if-else
  • Python lambda function example on square
  • Python lambda function example on cube
  • Python lambda function with reduce

Python Anonymous function

Python has two types of functions such as:

  1. Normal function:

A normal function in Python defined using the “def” keyword. We can write in multiple lines and it can have multiple expressions.

Example:

This is a simple program that displays the name & power of a pokemon. It accepts 2 arguments & displays the message.

Python normal function
def pokemon(name, power):
    return print(f'This is {name}, he can {power}.')

pokemon('pikachu', 'thunderbolt')

Output

This program accepts the name & power after that display message: This is pikachu, he can thunderbolt.

2. Anonymous function:

  • Python anonymous functions are also known as Lambda function. The keyword used is lambda and they are written in one line and it can have only one expression. These functions don’t need to be defined or named and they are for one-time usage.
  • Python Anonymous functions are popular among advance users as it saves time, effort & memory. though the code becomes less readable but works perfectly fine.

Python anonymous function with lambda

Let us see how to create a Python anonymous function with lambda.

  • Python Lambda function is a one-liner function with no name & used for a one-time task.
  • One-time tasks like performing arithmetic operations, sorting names, loops, etc.
  • It makes the code really small but the code becomes less readable as lambda is an advanced feature.

Syntax:

lambda parameter : action(parameter)

Example:

In this below example, there is a free upgrade provided to all the weapons players have. So whatever the level of weapon is now will be upgraded by 2.

Python anonymous function with lambda
Python anonymous function with lambda

Code:

weapon_level = [12, 14, 11, 9]
print("Weapon level before upgrade", weapon_level)
print("Weapon level before upgrade",list(map(lambda weapon: weapon + 2, weapon_level )))

You may like:

Python anonymous function without lambda

  • Python Anonymous functions are defined using the keyword ‘lambda‘, so technically there is no scope for anonymous function without lambda.
  • But there are instances that say that it can be done using constructors.
  • Constructors initiate the object of a class and are defined using keyword __init__ .
  • But on the other hand, it does not satisfy the condition of anonymous function. As anonymous functions are complete in itself, have no name & are used for a one-time task only.
  • In a conclusion, Constructors can’t be considered as an anonymous function.

Syntax:

class <Name>(object):
     def __init__(self, n1, n2):
         self.n1 = n1
         self.n2 = n2 

Example:

This is an example of Python constructor wherein player’s name & rank will be displayed.

Python anonymous function without lambda
Python anonymous function without lambda

Code:

class Game():
    def __init__(self, name, rank):
       self.name = name
       self.rank = rank

p1 = Game('Alpha', 1)
p2 = Game('Delta', 4)
print(p1.name, p1.rank)

Output:

Since we have printed details of p1 only so the output will be Alpha 1

Python anonymous function multiple lines

  • Anonymous functions are single-line commands or functions applied to a specific task.
  • Python lambda functions can have multiple arguments but only one expression.
  • So after reading the above statements, there is no way to create multiple lines lambda function.
  • It is advised to create normal function if the program has multiple expression.

Anonymous function as argument in Python

  • An argument is the input against the parameter.
  • if there is any parameter assigned to a function then that parameter needs a user argument as a value.
  • In add-function, if “a & b” are assigned as a parameter, then the user needs to provide input that will be placed in “a & b“. let’s say “2 & 3“. now it will give the output as “2+3 = 5”.

Example:

In this below example, user will provide an argument that will be added to total bill.

Python anonymous function as argument
anonymous function as argument in python

Code:

bill = lambda tip: tip + 10
print(bill(5))

So here, function is created & parameter ‘tip’ is passed. Now while printing, 5 is the bill + 10 as a tip so total it becomes 15. Here 5 is the argument.

Output:

In this example customer has purchased item of 5 & paid 10 as tip. So the output is 5 + 10 = 15. Here 5 is the argument provided by user.

Python anonymous function without argument

  • Argument is a value that needs to be passed while calling a function.
  • Argument makes the program dynamic.
  • But at times we want to provide static value to the program. In that situation, function is created without any parameter & users don’t need to provide any argument. Here in this below example, we will see an anonymous function without argument.

Syntax

variable_name = lambda : value
print(variable_name()) 

Example:

We are in a fruit market where every fruit has different defined price. We are printing the total price. This anonymous function do not have argument. so what ever function will be called associated price will be applied on it.

Python anonymous function without argument
Python anonymous function without argument

Code :

apple = lambda : 50
mango = lambda : 40
coconut = lambda : 35

print("Total:",apple()+mango())

Output:

Since apple and mango are called here so defined price 50 + 40 applied. Total becomes : 90

Anonymous function callback in Python

  • A one-liner statement to call a function is widely used among programmers.
  • In this, a predefined function is called single or multiple times using Python lambda function.
  • The most common example is ‘Calculators’, wherein the function is created & called through lambda function on each key individually.

Example:

This is the example of a calculator module wherein a button is printed when clicked. In the back-end it is calling function every time clicked.

Python anonymous function callback
anonymous function callback in python

Code :

from tkinter import *

numbers = "" 
def recClick(n): 
    global numbers
    numbers = numbers + str(n) 
    rec.set(numbers) 

if __name__ == "__main__": 
    w = Tk() 
    rec = StringVar() 
    disp = Entry(w, textvariable=rec).pack() 
    rec.set('') 
    Button(w, text=' 1 ', command=lambda: recClick(1)).pack()

    w.mainloop() 

Output:

The output of the code opens with the window have “TextField” & “Button“. Button keeping on printing 1 on the text field. Whenever a button is clicked a function is called.

Anonymous function multiple arguments

  • Multiple arguments can be passed to an anonymous function similar to normal functions.
  • There is no restriction on passing as many arguments as developers want but there can only be one expression.
  • In other words, the task will be just one irrespective of the arguments passed. Let’s understand it better with an example.

Example:

In this example, grocery store has multiple items. User purchased few of them. while checking-out the store manager manually provides the values to each item to generate the total bill.

Python anonymous function multiple arguments
Python anonymous function multiple arguments

Code:

grocery = lambda puls, frui, vege : puls + frui + vege
print("Total:",grocery(100, 150 , 75))

Output:

So here, multiple arguments in the form of 100, 50, 75 are passed & the output generated is 325 that is the sum of all the items.

Anonymous function in a Python dictionary

  • Python Anonymous functions are used to store a set of instructions in a Python dictionary and from that can be used when required.
  • It is implemented in the key-value format.
  • Lambda is implemented on value only.

Syntax:

name = {
     'unique-key-name' : lambda parameter : expression
}

Example:

In-game health, boost, upgrade, etc are stored in a dictionary & they are called whenever users click on the dedicated button. like when a user clicks on the heart icon, the health bar increases with some percentage.

Python anonymous function in a dictionary
Python anonymous function in a dictionary

Code:

extras = {
    'health' : lambda health : health + 5,
    'boost' : lambda speed : speed * 2,
    'upgrade' : lambda level : level + 1
}

print(extras['health'](5))
print(extras['boost'](100))
print(extras['upgrade'](10))

Output:

So, in this example user’s current health has been increased by 5 bars, speed is 2x and the level upgraded by 1. So the output doe the above code is 10, 200, 11.

Python anonymous function as a parameter

  • Parameters are the names used while creating functions.
  • def toys(p,b): p & b are the parameters here.
  • Parameter plays an important role as it adds flexibility to the program.
  • Parameters need input from the user.

Example:

In this example lambda function is called within a normal function as a parameter. Total bill at restaurant include sub_total ( price of food) + tip.

Python anonymous function as a parameter
Python anonymous function as a parameter

Code:

def restaurant(bill):
   return lambda tip :  tip + bill

sub_total = restaurant(200)
total = sub_total(20)
print(total)

Output:

The price for the food is 200 and 20 tip is provided. So the total amount to be paid by the customer is 200 + 20 = 220

Anonymous function using map in Python

  • Map function is used to simplify the program.
  • It takes function followed by iterations as an argument.
  • Map is one of the functions widely used by advanced programmers as it facilitates to implement of the function on each iteration individually.

Syntax:

map(function, iterations)


Example:

Due to a glitch in a game 10 coins are added to everyone’s wallet. Players have some balance already, now 10 more added to it. Let’s see this in a program.

Python anonymous function using map
Python anonymous function using map

Code:

cur_bal = [223, 112, 32, 71]
new_bal = lambda cur_bal : cur_bal + 10
print(list(map(new_bal, cur_bal)))

You might be thinking why we have used List here. Without list, it will give us only the memory location of the output. Here is the output without using the list.

<map object at 0x00000257F97A9648>

Output:

So the user’s current balance was [223, 112, 32, 71 ] but after the function is applied it becomes [233, 122, 42, 81 ]

Anonymous function examples in Python

Python anonymous function is one of the important concepts in python that can help you in reducing lines of code. Here are a few more examples of anonymous functions in Python.

Example:

  • In this, we are distributing chocolates & ice-creams. But the condition is below 10 will get chocolate & 10 & above will get ice-cream. We have used filter & map here. Filter is used to classifying students as per their age.
  • Map is used to show the age of students after 2 years. that means 2 is added at every iteration.

Filter :

  • It is a function used to filter the list items.
  • It takes function & iterations as an argument.
  • If in case the function is not applicable then None should be provided.

Syntax:

filter(function, iteration)
Python anonymous function example
anonymous function example in python

Code Snippet:

below_10 = lambda b10 : b10 < 10
above_10 = lambda a10 : a10 >= 10

student_age = [18, 10, 7, 16, 12, 5, 6, 8, 4]

below_ten = list(filter(below_10, student_age))
print("Chocolate: ",list(below_ten))

above_ten = list(filter(above_10, student_age))
print("ice cream : ", above_ten)

# age 2 years later
age_now = map(lambda age: age + 2, student_age)
print(list(age_now))

Output:

  • In first case students below 10 is displayed : Chocolate: [7, 5, 6, 8, 4]
  • In second case students above 10 is displayed: ice cream : [18, 10, 16, 12]
  • In third case students age after 2 years is displayed : [20, 12, 9, 18, 14, 7, 8, 10, 6]

The lambda function is an anonymous function that can take many arguments but have only one expression.

Python lambda function without if-else

Now, we can see lambda function without if-else in python

  • In this example, I have taken a variable as a number and used the lambda function, then used y > 5 and y < 25 conditions.
  • To get the output I have used print(number(10)) and print(number(30)).

Example:

number = lambda y : y > 5 and y < 25
print(number(10))
print(number(30))

The condition is valid for number 10, so the output is true and it is not valid for number 30 so the output is false. You can refer to the below screenshot for the output.

Python lambda function without if-else
Python lambda function without if-else

Python lambda function with filter

Now, we can see the lambda function with filter in python

  • In this example, I have taken the list as a number and assigned some values to the list as number = [3,6,10, 25, 17, 9, 30, -5].
  • The multiple_of_3 = list(filter(lambda n : n%3 == 0, number)) is used to get the new list.
  • To get the new list, I have taken the filter function. The filter() method constructs an iterator from the elements of an iterable.
  • The lambda functions run on all the numbers in the list and return the output.
  • The n%3 == 0 is used to get the multiples of 3 from the given list.
  • To get the output, I have used print(multiple_of_3).

Example:

number = [3,6,10, 25, 17, 9, 30, -5]
multiple_of_3 = list(filter(lambda n : n%3 == 0, number))
print(multiple_of_3)

In the below screenshot, you can see the multiples of 3 as the output.

Python lambda function with filter
Python lambda function with filter

Python lambda function with if-else

Here, we can see lambda function with if-else in python

  • In this example, I have taken a variable as a number and used the lambda x function, this function is having many arguments, and only one expression is evaluated and returned.
  • I have used the if-else condition, if the given value satisfies the if condition it returns a true else it returns false.
  • Here, I have taken two numbers like 12 and 30 and to get the output, I have used print(number(12)), print(number(30)).

Example:

number= lambda x : True if (x >= 2 and x < 20) else False
print(number(12))
print(number(30))

The number 12 satisfy the condition so it returned true and the number 30 does not satisfy the condition and it returned false. You can refer to the below screenshot for the output.

Python lambda function with if-else
Python lambda function with if-else

Python lambda function example on square

Here, we can see how to find the square of the number in python

  • In this example, I have defined a function square as a def square(y): and return y*y is used to calculate the square of the given number.
  • I have used the lambda function as square = lambda y: y*y. To get the output I have used print(square(4)).

Example:

def square(y): 
    return y*y
square = lambda y: y*y 
print(square(4)) 

We can see the square of 4 that is 16 as the output in the below screenshot.

Python lambda function square example
Python lambda function square example

Python lambda function example on cube

Now, we can see how to find a cube of the number using lambda function in python

  • In this example, I have defined a function cube as a def cube(y):, and to calculate the cube value I have used return y*y*y, and lambda function is used cube = lambda y: y*y*y.
  • To get the output I have used print(cube(2)).

Example:

def cube(y): 
    return y*y*y
cube = lambda y: y*y*y
print(cube(2)) 

We can see the cube of 2 that is 8 as an output. You can refer to the below screenshot for the output.

cubes
Python lambda function cube example

Python lambda function with reduce

Now, we can see lambda function with reduce in python

  • The reduce function is used to apply a particular function passed in its arguments to all the elements from the list.
  • In this example, I have imported a module called reduce from functools, I have defined a list as list = [2,4,5]and declared a variable called sum to store the reduced value.
  • The lambda function runs on all the items on the list and it returns the product of all the numbers from the list.
  • I have used print(sum) to print the result returned by the reduce function.

Example:

from functools import reduce
list = [2,4,5]
sum = reduce (lambda a, b: a*b, list)
print(sum)

You can see the product of all the numbers in the list as the output in the below screenshot.

Python lambda function with reduce
Python lambda function with reduce

You may like the following Python tutorials:

ou may like the following Python tutorials:

In this python tutorial, we learned:

  • What is Python Anonymous function
  • What is Lambda function in python
  • Python anonymous function with lambda
  • Anonymous function without lambda in Python
  • Anonymous function multiple lines
  • Anonymous function as an argument
  • Anonymous function without argument in Python
  • Python anonymous function example
  • Anonymous function callback in Python
  • Anonymous function multiple arguments in Python
  • Python anonymous function in a dictionary
  • Python anonymous function as a parameter
  • Python anonymous function map
  • Python lambda function without if-else
  • Python lambda function with filter
  • Python lambda function with if-else
  • Python lambda function example on square
  • Python lambda function example on cube
  • Python lambda function with reduce