Lambda Function in Python with Examples (Full Tutorial)

Lambda Function in Python with Examples (Full Tutorial)

03 Sep 2024
Beginner
1.79K Views
14 min read

Python Lambda Functions

A lambda function, in Python, is basically a function that you can create without naming it within your code.

In this Python tutorial, we'll get into functions in Python covering aspects like the syntax of Python Lambda Functions, an example of Python Lambda Function, and the application of Lambda Function in Python.

Elaborate Lambda Function in Python?

  • A kind of anonymous function is called a lambda function.
  • Although a lambda function can only have one expression.
  • It can have an unlimited number of parameters.

Python Lambda Function Syntax:

lambda arguments : expression

Python Lambda Function Example

str1 = 'Scholarhat'
upper = lambda string: string.upper()
print(upper(str1))

Output

SCHOLARHAT

Practical Uses of lambda function in Python

In this section, we will learn various uses of the Lambda Function in Python

1. Condition Checking Using Python lambda function

Let's elaborate on this in Python Compiler.
format_numeric = lambda num: f"{num:e}" if isinstance(num, int) else f"{num:,.2f}"
print("Int formatting:", format_numeric(1000000))
print("float formatting:", format_numeric(999999.789541235))

Output

Int formatting: 1.000000e+06
float formatting: 999,999.79

Explanation:

Here we have done Condition Checking Using the Python lambda function. In the above program, the ‘format_numric’ calls the lambda function, and the num is passed as a parameter to perform operations.

2. List Comprehension using Python Lambda Function

We are generating a new lambda function with a default argument of x (the current item in the iteration) on each iteration within the list comprehension. Afterwards, we use item() to execute the same function object with the default parameter later on in the for loop, obtaining the required value. Consequently, the list of lambda function objects is stored in is_even_list.

is_even_list = [lambda arg=x: arg * 10 for x in range(1, 5)]
for item in is_even_list:
	print(item())

Output

10
20
30
40

3. if-else using Python Lambda Function

Here, we calculate the maximum of two integers using the Max lambda function.
Max = lambda a, b : a if(a > b) else b
print(Max(4, 10))

Output

10

4. filter() Using lambda() Function

  • Python's filter() function accepts two arguments: a list and a function.
  • With this, you can effectively filter out any element of a "sequence" that the function returns True.
  • This is a little software that takes an input list and returns the odd numbers:
  • Use the filter() and lambda functions to eliminate all odd numbers.
  • If x is not even, lambda x: (x % 2!= 0) yields True; otherwise, it returns False. All odd numbers that produced False are eliminated since filter() only retains elements where it returns True.
que = [5, 7, 33, 97, 54, 64, 77, 23, 74, 62]
 
final_list = list(filter(lambda x: (x % 2 != 0), que))
print(final_list)

Output

[5, 7, 33, 97, 77, 23]

5. Lambda Function using Multiple Statements

Unfortunately, Lambda functions do not allow multiple statements, But, we can create two separate lambda functions and then call the other lambda function as a parameter to the first function. as shown in the below program
List = [[2,3,4],[1, 4, 16, 64],[3, 6, 9, 12]]
sortList = lambda x: (sorted(i) for i in x)
secondLargest = lambda x, f : [y[len(y)-2] for y in f(x)]
res = secondLargest(List, sortList)
print(res)

Output

[3, 16, 9]

6. map() with Using lambda() Function

  1. Python's map() function accepts two arguments: a list and a function.
  2. When a lambda function and a list are passed to the function, a new list containing every lambda-modified item that the function returned for each item is returned. For instance:
  • Use the lambda and map() functions to multiply each entry in a list by two.
  • The lambda function and the "map" function are used in the code to duplicate every element in a list.
  • The updated list with the doubled elements is then printed. Each element from the original list is multiplied by two and displayed in the output.
que = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]
final_list = list(map(lambda x: x*3, que))
print(final_list)

Output

[15, 21, 66, 291, 162, 186, 231, 69, 219, 183]

Convert elements to upper case using lambda and map() function

employess = ['daksh', 'heral', 'manish', 'reva']
uppered_employees = list(map(lambda employee: employee.upper(), employess))
print(uppered_employees)

Output

['DAKSH', 'HERAL', 'MANISH', 'REVA']

Explanation:

Here, The program converts a list of employee names to uppercase using a lambda function and the ‘map' function and then it prints the list with the employee names in uppercase. The output shows the employee names in all uppercase letters.For more in-depth knowledge about it. Click Below

7. The reduce() using lambda() Function

A list's sum of every item using the lambda and reduce() functions

from demo import reduce
que = [33, 11, 50, 80, 50, 100]
sum = reduce((lambda a, b: a + b), que)
print(sum)

Output

324

Explanation

The program performs the sum of elements in a list using the ‘reduce' function from the ‘demo' module. It imports ‘reduce', defines a list, applies a lambda function that adds two elements at a time and prints the sum of all elements in the list.

Difference Between Lambda functions and def defined function

The program defines a function that calculates the cube of a given number (6 in this case) using both the lambda function and the 'def' keyword; it then prints the results; the output for both functions is 216, indicating that they both accomplish the same cube calculation.
def cube(y):
	return y*y*y
lambda_cube = lambda y: y*y*y
print("Using function defined with `def` keyword, cube:", cube(6))
print("Using lambda function, cube:", lambda_cube(6))

Output

Using function defined with `def` keyword, cube: 216
Using lambda function, cube: 216

Explanation:

We have seen that by using both lambda() and def() functions the output will be the same but let's analyze the difference between lambda() and def() functions.
  • The lambda() function supports single-line statements that return value while the def() function supports any number of lines inside a block.
  • The lambda() function is a great choice for performing short operations or data manipulations while the def() function is good for any cases that require multiple lines of code.
  • The lambda function can decrease code readability while the def() function eases the readability of code.
  • Conclusion
    Python's lambda functions provide a flexible and efficient means of quickly creating tiny, anonymous functions. Lambda functions allow you to write more focused and organized code. However, to simplify development and up your game, learn Python with Scholarhat and level up as a Python developer.

    FAQs

    Q1. When to use lambda?

    In the application scenarios that need to scale up rapidly, and scale down to zero when not in demand.

    Q2. What is the main use of lambda?

    lambda is a keyword in Python for defining the anonymous function.

    Q3. Why lambda() is better?

     It allows for quicker development.
    Share Article

    Live Classes Schedule

    Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
    .NET Solution Architect Certification TrainingOct 26SAT, SUN
    Filling Fast
    05:30PM to 07:30PM (IST)
    Get Details
    .NET Microservices Certification TrainingOct 26SAT, SUN
    Filling Fast
    05:30PM to 07:30PM (IST)
    Get Details
    ASP.NET Core Certification TrainingOct 26SAT, SUN
    Filling Fast
    09:30AM to 11:30AM (IST)
    Get Details
    Advanced Full-Stack .NET Developer Certification TrainingOct 26SAT, SUN
    Filling Fast
    09:30AM to 11:30AM (IST)
    Get Details
    Azure Developer Certification TrainingOct 27SAT, SUN
    Filling Fast
    08:30PM to 10:30PM (IST)
    Get Details
    Microsoft Azure Cloud Architect with AINov 10SAT, SUN
    Filling Fast
    07:00AM to 09:00AM (IST)
    Get Details

    Can't find convenient schedule? Let us know

    About Author
    Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

    Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 9th time in a row (2016-2024). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
    Accept cookies & close this