Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Lambda Function in Python

Last Updated on May 18, 2023 by Prepbytes

The lambda function in Python is one of the most interesting topics because it allows you to write a function on a single line. It’s incredible that Python lambda can do that. Python’s lambda function provides a very elegant method for performing difficult tasks with ease. We will go over how the lambda function works and how to use it in Python. Let’s start with the basics of our topic, "Lambda Function in Python."

What is Lambda Function in Python?

Python Lambda Functions are anonymous functions or functions without a name. A standard Python function, as we know, is defined with the def keyword. Python uses the lambda keyword in this manner to define an anonymous function.

Syntax of Lambda Function in Python

The syntax for Python lambda is provided below.
Syntax

lambda arguments: expression
  • There is only one expression that is evaluated and returned in this function, regardless of the number of parameters.
  • Lambda functions can be used anywhere that function objects are required.
  • The fact that lambda functions are syntactically limited to a single expression must always be kept in mind.
  • In addition to several kinds of expressions in functions, it has a variety of purposes in specific programming disciplines.

Python Lambda Function Example

str1 = 'prepbytes'
# lambda returns a function object
rev_upper = lambda string: string.upper()[::-1]
print(rev_upper(str1))

Output:

SETYBPERP

Explanation: In the example above, we constructed a lambda function called rev upper to reverse and convert a string to uppercase.

Use of Lambda Function in Python

Here, we will see different examples using lambda function in python.

Example 1 of Using a Lambda Function in Python for the checking

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

Example 2 of Distinguishing Lambda functions from def defined functions
def cube(y):
return yyy
lambda_cube = lambda y: yyy

# using function defined
# using def keyword
print("Using function defined with def keyword, cube:", cube(3))

# using the lambda function
print("Using lambda function, cube:", lambda_cube(3))

Output:

Using function defined with def keyword, cube: 27
Using lambda function, cube: 27

The cube() function and lambda cube() function perform identically and as intended, as can be seen in the example above. Let’s examine the case from above in more detail:

  • With lambda function
  • Without lambda function
  • Supports single line statements that return some value.
  • Supports any number of lines inside a function block
  • Good for performing short operations/data manipulations.
  • Good for any cases that require multiple lines of code.
  • Using lambda functions can sometimes reduce the readability of code.
  • We can use comments and function descriptions for easy readability.

Practical Applications of Lambda Function in Python

Let’s look at how python lambda is used in practice in the coding world.

Example 1: List Comprehension Using Python lambda Function
We’ll use the lambda function and list comprehension in this example.

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

# iterate on each lambda function
# and invoke the function to get the calculated value
for item in is_even_list:
    print(item())

Output:

10
20
30
40

Explanation: We are generating a new lambda function with the default argument of x on each iteration of the list comprehension (where x is the current item in the iteration). We later call the same function object with the default argument using item() inside the for loop to obtain the desired value. As a result, the list of lambda function objects is stored in its even list.

Example 2: Lambda function in Python with if-else
Here we are using Max lambda function to find the maximum of two integers.

# Example of lambda function using if-else
Max = lambda a, b : a if(a > b) else b
print(Max(1, 2))

Output:

2

Example 3: Python Lambda statements with several lines
Although multiple statements are not permitted in lambda functions, we can create two lambda functions and then call one of them as a parameter to another. Let’s use lambda to search for the second greatest element.

List = [[2,3,4],[1, 4, 16, 64],[3, 6, 9, 12]]

# Sort each sublist
sortList = lambda x: (sorted(i) for i in x)

# Get the second largest element
secondLargest = lambda x, f : [y[len(y)-2] for y in f(x)]
res = secondLargest(List, sortList)
print(res)

Output:

[3, 16, 9]

Explanation: Each sublist of the given list is sorted in the example above using a lambda function. The second lambda function receives this list as an input and returns the n-2th entry from the sorted list, where n is the length of the sublist.

Along with built-in functions like filter(), map(), and reduce(), lambda functions can be employed. When combined with methods like filter(), map(), reduce(), etc., lambda functions can unleash their full potential.

Using Python Lambda with the filter Function

The filter() function in Python takes two arguments: a function and a list. This is a sophisticated method for removing all sequence "sequence" components for which the function returns True. The program below extracts the odd numbers from the input list:

Example 1: Utilize the lambda function and filter() to obtain all odd numbers.
If x is not even, the lambda expression x: (x% 2!= 0) return True or False. Since filter() only retains elements that result in True, all odd numbers that produced False are eliminated.

li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]

final_list = list(filter(lambda x: (x % 2 != 0), li))
print(final_list)

Output:

[5, 7, 97, 77, 23, 73, 61]

Example 2: Use the lambda and filter() functions to filter out anyone older than 18

# Python 3 code to people above 18 yrs
ages = [13, 90, 17, 59, 21, 60, 5]

adults = list(filter(lambda age: age > 18, ages))

print(adults)

Output:

[90, 59, 21, 60]

Using lambda() Function with map()

The map() method in Python takes two arguments: a function and a list. When the function is invoked with a lambda function and a list, it returns a new list containing all the lambda-modified items returned by that function for each item. Let’s look at an example of how to use the map function with the lambda function in Python:

Example 1: Use python lambda and the map function to multiply every element of a list by two.

# Python code to illustrate
# map() with lambda()
# to get double of a list.
li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]

final_list = list(map(lambda x: x*2, li))
print(final_list)

Output:

[10, 14, 44, 194, 108, 124, 154, 46, 146, 122]

Example 2: Utilize lambda and the map() function to convert all list elements to uppercase.

# Python program to demonstrate
# use of lambda() function
# with map() function
animals = ['dog', 'cat', 'parrot', 'rabbit']

# here we intend to change all animal names
# to upper case and return the same
uppered_animals = list(map(lambda animal: animal.upper(), animals))

print(uppered_animals)

Output:

['DOG', 'CAT', 'PARROT', 'RABBIT']

Using reduce and the lambda function

Python’s reduce() function accepts two arguments: a function and a list. A lambda function and iterable are used to invoke the function, and a new reduced result is returned. This repeatedly operates on the iterable’s pair of pairs. The functools module contains the reduce() method.

Example 1: Using lambda() and reduce(), calculate the sum of all the elements in a list.

# Python code to illustrate
# reduce() with lambda()
# to get sum of a list

from functools import reduce
li = [5, 8, 10, 20, 50, 100]
sum = reduce((lambda x, y: x + y), li)
print(sum)

Output:

193

In this case, the outcomes of the preceding two elements are added to the following element, and so on until the last element, as in (((((5+8)+10)+20)+50)+100).

Example 2: Using the lambda and reduce() functions, find the most frequently occurring element in a list.

# python code to demonstrate working of reduce()
# with a lambda function

# importing functools for reduce()
import functools

# initializing list
lis = [1, 3, 5, 6, 2, ]

# using reduce to compute maximum element from list
print("The maximum element of the list is : ", end="")
print(functools.reduce(lambda a, b: a if a > b else b, lis))

Output:

The maximum element of the list is : 6

Conclusion
We have now completed our tutorial on the lambda function in Python. We discussed what is lambda function in Python, what its syntax is, how to use it, and how to use lambda with the filter, reduce, and map functions. The Python lambda function can be used in a variety of contexts, and its features are used to create code that is clear and straightforward. The lambda function in Python is an intriguing topic; if you are a beginner, you should experiment with it because it will improve your coding skills in the long run.

Frequently Asked Questions (FAQs)

Q1. What do you call a lambda function in Python?
Ans. We can declare a lambda function and call it as an anonymous function, without assigning it to a variable. Above, lambda x: xx defines an anonymous function and call it once by passing arguments in the parenthesis (lambda x: xx).

Q2. What are the advantages of lambda function?
Ans. Lambda enables you to use functions with pre-trained machine learning (ML) models to inject artificial intelligence into applications more easily. A single application programming interface (API) request can classify images, analyze videos, convert speech to text, perform natural language processing, and more.

Q3. What is the difference between lambda and DEF in Python?
Ans. Lambda Function, often known as an ‘Anonymous Function,’ is the same as a normal Python function except that it can be defined without a name. The def keyword is used to define normal functions, while the lambda keyword is used to define anonymous functions. They are, however, limited to a single line of expression.

Leave a Reply

Your email address will not be published. Required fields are marked *