Tutorial Gateway

  • C
  • C#
  • Java
  • Python
  • SQL
  • MySQL
  • Js
  • BI Tools
    • Informatica
    • Talend
    • Tableau
    • Power BI
    • SSIS
    • SSRS
    • SSAS
    • MDX
    • R Tutorial
    • Alteryx
    • QlikView
  • More
    • C Programs
    • C++ Programs
    • Go Programs
    • Python Programs
    • Java Programs

Python Lambda Function

by suresh

The Python lambda function is anonymous means, a function without a definition keyword and name. To create a Python lambda function, we have to use the lambda keyword. The syntax of the Python lambda expression is

lambda arguments: expression

The Python lambda function accepts any number of arguments. However, lambda takes only one expression. For instance, lambda a, b: a + b. Here, a and b are the arguments accepted by the Python lambda function. a + b is the expression.

Python lambda Examples

The following list of examples helps to learn the Python lambda functions.

Python lambda with No Arguments

Use the following lambda statement to display the True or False as an output. It can make you understand that you do not need any argument to create a lambda expression in Python.

# Python Lambda Example

num = lambda: True

print(num())
Python Lambda Example 1

Python lambda Sum

We are using the lambda expression to add 5 to the given argument value. It accepts one value because we specified one argument after the lambda keyword. After the colon, it is an expression or the functionality it has to perform when we call this anonymous lambda function.

num = lambda x: x + 5

print(num(10))

As you can see from the Python image below, we passed 10 as an argument. 10 + 5 = 15.

Python Lambda Example 2

In this Python lambda Sum example, we are using two arguments to perform addition or find the sum of two numbers. It means we have to assign two values while calling this lambda expression.

add = lambda x, y : x + y

print(add(10, 20))
Python Lambda Example 3

Generally, we can achieve the same by declaring or creating a Function. This time, we are using the Python lambda expression and regular function. Both give the same result.

add = lambda x, y : x + y
print(add(10, 20))

print("\nResult from a Function")
def add_func(x, y):
   return x + y

print(add_func(10, 20))

As you see, both lambda and regular functions are returning the same result. However, the regular function needs a def keyword, function name, and a return value. Whereas, lambda function does not need any of them. By default, it returns the expression result.

Python Lambda Example 4

Lambda expressions are not about adding two values. We can perform multiplication, subtractions, or any other calculations. Here, we are multiplying two argument values. For better understanding of the lambda expressions, we are placing the regular function as well.

multi = lambda x, y : x * y
print(multi(5, 20))

print("\nResult from a multi Function")
def multi_func(x, y):
    return x * y

print(multi_func(5, 20))
Python Lambda Example 5

Python lambda Mulitple Values

In this lambda example, we are using three-arguments. Next, we are multiplying those three argument values.

multi = lambda x, y, z : x * y * z
print(multi(5, 2, 6))

print("\nResult from a multi Function")
def multi_func(x, y, z):
    return x * y * z

print(multi_func(5, 2, 6))
Python Lambda Example 6

Until now, we used this lambda expression to calculate something and returning results. However, use the print statement to print the lambda output as well. Below lambda code prints Hello World! as an output.

message = lambda: print("Hello World!")

message()
Python Lambda Print statement 7

We can also achieve the same result by calling that lambda statement with parenthesis.

Python Lambda Example 8

Python lambda Default Argument Values

In this lambda expression example, we assigned default values to all three arguments. Next, we are adding, multiplying, and subtracting them. If we have the default values, we do not have to pass values while calling the Python lambda expression.

# Python Lambda Example

add = lambda x = 10, y = 20, z = 30 : x + y + z
print(add()) # 10 + 20 + 30

multi = lambda x = 10, y = 20, z = 30 : x * y * z
print(multi()) # 10 * 20 * 30

sub = lambda x = 10, y = 45: y - x
print(sub()) # 45 - 10
Python Lambda Example 9

However, you can override the default values by passing new values as the arguments. Here, the first print statement overrides 10 with 12, 20 with 14 and 30 with 16. It means, x = 12, y = 14 and z = 16. In the second statement, x = 75, y = 126 and z = 30.

add = lambda x = 10, y = 20, z = 30 : x + y + z
print(add(12, 14, 16)) # 12 + 14 + 16
print(add(75, 126)) # 75 + 126 + 30
print(add(222)) # 222 + 20 + 30
print(add()) # 10 + 20 + 30

print("Multiplication Values")
multi = lambda x = 10, y = 20, z = 30 : x * y * z
print(multi(2, 4, 5)) # x = 2, y = 4, z = 5
print(multi(100, 22)) # x = 100, y = 22, z = 30
print(multi(9)) # x = 9, y = 20, z = 30
print(multi()) # 10 * 20 * 30
Python Lambda Default Values 10

Python lambda Without Arguments

If you don’t want to pass any arguments, however, you want to return something from the lambda, then you can use this kind of statement.

We do not have to pass any argument values to call these lambda expressions. Whenever we call them, they return the same result.

add = lambda : 10 + 20
print(add())

print("Multiplication Values")
multi = lambda : 10 * 20
print(multi())

print("Subtraction")
sub = lambda : 225 - 20
print(sub())
Python Lambda Without Arguments 11

Anonymous Functions using lambda

Python lambda function is powerful when we use this anonymous function inside a function. Here, we declared a function that accepts one argument. Inside the function, we used a Python lambda expression to multiply that value with the unknown number of times.

# Python Anonymous Functions Lambda Example

def new_func(n):
    return lambda x : x * n

number = new_func(2)

print(number(50))
Python Anonymous Functions using Lamba 12

It calls new_func function where n = 2. It means, function returns lambda x: x * 2. Then, we assigned that value to the number (lambda object)

number = new_func(2)

Next, we called that number with 50 (this is lambda argument value. It means, lambda 50 : 50 * 2 => 100

Calling the lambda function with different values. First with 2, and then with 3.

def new_func(n):
   return lambda x : x * n

number1 = new_func(2)
number2 = new_func(3)

print(number1(50))
print(number2(50))
Python Anonymous Functions using Lamba 13

Lambda with Built-in Functions

In Python, we can use the available Built-in functions along with lambda function.

Python lambda filter Example

We use the built-in filter function to filter the sequence of list items. First, we declared a list of numbers from 1 to 15. Next, we used the filter function with a lambda expression. 

This Python lambda expression checks whether a number is divisible by two or not. Next, the filter function returns all the True values.

TIP: Refer to the Python List article.

number = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
print(number)

new_num = list(filter(lambda x : x % 2 == 0, number))
print(new_num)
Python Lambda Filter Example 14

Here, we extended the previous Python lambda example. This lambda code filters and returns the Even Number, Odd Numbers, and Numbers that are divisible by 3.

number = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
print(number)

even_num = list(filter(lambda x : x % 2 == 0, number))
print(even_num)

odd_num = list(filter(lambda x : x % 2 != 0, number))
print(odd_num)

num_div_by_3 = list(filter(lambda x : x % 3 == 0, number))
print(num_div_by_3)
Python Lambda Filter Example 15

Lambda map Example

Unlike filter function, map function takes each list item and returns both the True and False values. In this Python lambda example, we used map function to return the boolean value. It checks each individual value is divisible by 2 equals to 0. If true, it returns True. Otherwise, it returns false.

number = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(number)

new_num = list(map(lambda x : x % 2 == 0, number))
print(new_num)
Python Lambda Map Example 16

This time, we are performing multiplication using this Python lambda map function. It takes one individual list item at a time and performs the multiplication. At last, lambda expression returns the modified list.

number = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(number)

double_num = list(map(lambda x : x * 2, number))
print(double_num)

triple_num = list(map(lambda x : x * 3, number))
print(triple_num)

square_num = list(map(lambda x : x ** 2, number))
print(square_num)
Python Lambda Map Example 17

By using the map function, you can also perform calculations on multiple lists. For instance, this Python lambda example performs addition, subtraction, and multiplication of two lists. It takes one value from both the list in the same position and performs the calculation.

number1 = [10, 20, 30]
number2 = [15, 25, 35]
print(number1)
print(number2)

print("***********==========*************")
add_num = list(map(lambda x, y : x + y, number1, number2))
print(add_num)

sub_num = list(map(lambda x, y : x - y, number1, number2))
print(sub_num)

mul_num = list(map(lambda x, y : x * y, number1, number2))
print(mul_num)
Python Lambda Map Example 18

ANALYSIS

add_num = list(map(lambda x, y : x + y, number1, number2))

First, x = 10 from number1, y = 15 from number2 list. By adding both of them get 25.

Lambda Reduce Example

The Python lambda reduce function accepts two values and a list as arguments values. Using this reduce function along with the lambda function.

from functools import reduce
number = [10, 20, 30, 15, 25, 35, 45]
print(number)

print("***********==========*************")
add_num = reduce((lambda x, y : x + y), number)
print(add_num)

sub_num = reduce((lambda x, y : x - y), number)
print(sub_num)

mul_num = reduce((lambda x, y : x * y), number)
print(mul_num)
Python Lambda Reduce Example 19

ANALYSIS

number = [10, 20, 30, 15, 25, 35, 45]
add_num = reduce((lambda x, y : x + y), number)

First, x = 10, y = 20. Or write it as ((((((10 + 20) + 30) + 15) + 25) + 35) + 45)

Lambda Built-in function Example

Until now, we are using the Python lambda expression to calculate something or performing numerical operations. However, you can use them on string data as well.

In this lambda function example, we declared a string list. Next, we used the sorted function to sort the list items. However, we used the sorted key as a lambda expression. Within this expression, we are using the len function to find the length of each word. It means sorting is done based on the item length.

x = ['apple', 'Mango Fruit', 'Banana', 'oranges', 'cherry','kiwi']
print(x)

y = sorted(x, key = lambda a: len(a))
print(y)

z = sorted(x, key = lambda a: a.casefold())
print(z)
Python Lambda Example 20

Placed Under: Python

  • Download and Install Python
  • Python Arithmetic Operators
  • Python Assignment Operators
  • Python Bitwise Operators
  • Python Comparison Operators
  • Python Logical Operators
  • Python If Statement
  • Python If Else
  • Python Elif Statement
  • Python Nested If
  • Python For Loop
  • Python While Loop
  • Python Break
  • Python Continue
  • Python Dictionary
  • Python datetime
  • Python String
  • Python Set
  • Python Tuple
  • Python List
  • Python List Comprehensions
  • Python Lambda Function
  • Python Functions
  • Python Types of Functions
  • Python Iterator
  • Python File Handling
  • Python Directory
  • Python Class
  • Python classmethod
  • Python Inheritance
  • Python Method Overriding
  • Python Static Method
  • Connect Python and SQL Server
  • Python SQL Create DB
  • Python SQL Select Top
  • Python SQL Where Clause
  • Python SQL Order By
  • Python SQL Select Statement
  • Python len Function
  • Python max Function
  • Python map Function
  • Python print Function
  • Python sort Function
  • Python range Function
  • Python zip Function
  • Python Math Functions
  • Python String Functions
  • Python List Functions
  • Python NumPy Array
  • NumPy Aggregate Functions
  • NumPy Arithmetic Operations
  • Python Numpy Bitwise operators
  • Numpy Comparison Operators
  • Numpy Exponential Functions
  • Python Numpy logical operators
  • Python numpy String Functions
  • NumPy Trigonometric Functions
  • Python random Array
  • Python numpy concatenate
  • Python numpy Array shape
  • Python pandas DataFrame
  • Pandas DataFrame plot
  • Python Series
  • Python matplotlib Histogram
  • Python matplotlib Scatter Plot
  • Python matplotlib Pie Chart
  • Python matplotlib Bar Chart
  • Python List Length
  • Python sort List Function
  • Python String Concatenation
  • Python String Length
  • Python substring
  • Python Programming Examples

Copyright © 2021 · All Rights Reserved by Suresh

About Us | Contact Us | Privacy Policy