1. Home
python

Python Tutorials - Elevate Your Coding Skills with Comprehensive Tutorials

Discover Python tutorials covering everything from the basics to advanced topics. Whether you're new to programming or looking to level up your skills, our tutorials will guide you every step of the way

  • 201 Lessons
  • 33 Hours
right-top-arrow

Tutorial Playlist

200 Lessons
38

Lambda and Anonymous Function in Python

Updated on 19/07/20244,599 Views

Introduction

In this tutorial, we embark on an insightful exploration into one of the most elegant and powerful constructs: lambda and anonymous function in Python. Tailored meticulously for professionals aiming to refine their Python expertise, this guide delves deep into these tools, revealing their significance and efficacy. As we traverse this journey, you will gain an understanding of how these constructs can profoundly transform the way you approach certain coding scenarios, especially when precision and conciseness are paramount.

Overview

Python, celebrated for its adaptability and effectiveness, offers developers an expansive toolkit for crafting functions. Among this diverse set, lambda and anonymous function in Python are particularly intriguing. Their conciseness, combined with their versatility, sets them apart, making them invaluable tools for developers who are eager to write cleaner, more streamlined code. This tutorial sets the stage, offering a glimpse into these functions' potency and how, despite their succinct nature, they play a pivotal role in a Python programmer's repertoire.

Defining Lambda Functions in Python

Python, with its array of functional programming tools, introduces the concept of lambda functions, which have their roots in lambda calculus. Lambda functions, often referred to as "anonymous functions", deviate from traditional Python functions in that they are not defined using the standard def keyword, nor do they bear a specific name. Instead, they embrace a concise approach, realized through the lambda keyword.

The quintessential structure of a lambda function is: lambda arguments: expression. In this compact form, while there can be multiple arguments, only one expression is allowed. This expression gets evaluated and its result is returned immediately, making lambda functions highly efficient for certain scenarios.

Drawing a comparison between regular functions and lambda functions offers a clearer perspective:

  • Definition Keyword: Traditional functions employ the def keyword, whereas lambda functions use lambda.
  • Naming: While regular functions are named and can be invoked using this given name, lambda functions are inherently anonymous, often utilized for one-time operations and discarded.
  • Return Statements: Regular functions may contain the return keyword to send back results. In contrast, lambda functions automatically return the value of their lone expression.
  • Expression Limit: While a standard function might encompass multiple expressions or statements, lambda functions are restricted to just a singular expression.
  • Application: Regular functions are versatile and can handle a plethora of tasks. Lambda functions, on the other hand, shine in specific situations, such as when working with functions like map(), filter(), or sorted().

Lambda functions offer distinct advantages:

  1. Brevity: Their one-liner nature ensures clarity and enhanced readability in code.
  2. Transience: Since they're unnamed, they're perfect for transient use cases where a formal function name might be overkill.
  3. Flexibility: Their compatibility with various Python functions like map(), filter(), and sorted() makes them highly adaptable.

Lambda Function Syntax in Python

The basic syntax of a lambda function is as follows:

lambda arguments: expression

In the above syntax,

  • arguments are the input parameters that the lambda function takes, separated by commas.
  • expression is a single expression that is evaluated and returned as the result of the lambda function.

Lambda Function Example in Python

Code:

# A lambda function that squares a number
square = lambda x: x**2

# Using the lambda function
result = square(4)
print(result)  # Output: 16

The Use of Lambda Functions in Python

Lambda functions in Python are typically used for short, simple operations where defining a full-fledged named function using the def keyword would be more verbose. They are often employed in scenarios such as:

  • Sorting: You can use lambda functions to customize the sorting order based on specific criteria.
  • Filtering: Lambda functions are handy for filtering data based on specific conditions.
  • Mapping: You can use lambda functions to transform elements of a collection.
  • Anonymous Functions: When you need a small, disposable function for a specific task.
  • Key Functions: For providing custom sort keys when sorting complex data structures.
  • Callbacks: As arguments to higher-order functions that accept functions as parameters.
  • Reducing Redundancy: In cases where you need a function that's used only once or in a limited scope, lambda functions can reduce code redundancy.

Lambda functions are especially useful for concise, one-off operations. However, for more complex logic, it's often better to use a regular named function defined with def. The choice between a lambda function and a regular function depends on the specific requirements and readability of your code.

Differences Between Lambda Functions and def Defined Functions in Python

Lambda functions and functions defined using the def keyword in Python both serve the purpose of defining functions, but they have some key differences. Here's a comparison of lambda functions and def defined functions:

Lambda functions:

  • Anonymous Functions: Lambda functions are anonymous functions, meaning they don't have a name. They are defined using the lambda keyword followed by arguments and an expression.
Example: lambda x, y: x + y
  • Single Expression: Lambda functions are limited to a single expression, which is evaluated and returned as the result of the function.They are typically used for short, simple operations.
  • Concise Syntax: Lambda functions have a concise syntax, which is useful for writing short, inline functions.
  • Inline Usage: Lambda functions are often used inline within other expressions or as arguments to higher-order functions like map(), filter(), and sorted().
  • Limited Scope: Lambda functions are typically used for small, specific tasks and are not well-suited for complex logic.

Functions defined with def:

  • Named Functions: Functions defined with def have names and can be called by their names.
Example: def add(x, y): return x + y
  • Multiple Statements: Functions defined with def can contain multiple statements and have more complex logic. They are suitable for longer and more involved operations.
  • Reusability: def defined functions can be reused in multiple parts of your code, making them more versatile.
  • Readability: Named functions defined with def can improve code readability, especially when the function performs a complex task or has a descriptive name.
  • Full Function Structure: Functions defined with def can have docstrings for documentation, default argument values, and more.

Example comparing lambda and def functions:

Lambda function example:

add = lambda x, y: x + y
result = add(3, 5)

def defined function example:

def add(x, y):
    return x + y

result = add(3, 5)

In summary, the choice between lambda functions and def defined functions depends on your specific needs. Lambda functions are suitable for short, simple tasks, while def defined functions are more versatile and appropriate for complex logic, reusability, and improved code readability.

Example Uses of Python Lambda Function

List Comprehension With Python Lambda Function

Code:

is_eve_list = [lambda arg=x: arg * 10 for x in range(1, 7)]
for i in is_eve_list:
print(i())

Explanation:

1. The range(1, 7) generates a sequence of numbers from 1 to 6 (inclusive).

2. The list comprehension [lambda arg=x: arg * 10 for x in range(1, 7)] iterates over each number in the range and creates a lambda function for each number.

  • For each number x in the range, it defines a lambda function with the argument arg, which defaults to the value of x.
  • Inside each lambda function, it calculates and returns arg * 10.

3. The for loop iterates over each lambda function in the is_eve_list.

4. Inside the loop, each lambda function is called without any arguments using i(). Since each lambda function has a default argument arg that is set to the corresponding value from the range(1, 7) during its creation, calling i() essentially calculates x * 10 for each value of x in the range.

5. The print() function is used to display the result of each lambda function, which is the product of the current x value multiplied by 10.

Lambda Function With if-else in Python

Code:

# Lambda function with if-else to check if a number is even or odd
even_odd = lambda x: "Even" if x % 2 == 0 else "Odd"

# Test the lambda function
print(even_odd(4))  # Output: Even
print(even_odd(7))  # Output: Odd

Explanation:

  • The lambda function lambda x: "Even" if x % 2 == 0 else "Odd" takes one argument x.
  • It checks if x % 2 == 0 to determine if x is even.
  • If the condition is true, it returns "Even"; otherwise, it returns "Odd."

Lambda With Multiple Statements in Python

Code:

L = [[2,5,4],[1, 3, 16, 54],[1, 6, 10, 12]]
sort_L = lambda x: (sorted(i) for i in x)
sec_Lar = lambda x, f : [y[len(y)-2] for y in f(x)]
result = sec_Lar(L, sort_L)
print(result)

Explanation:

  • sort_L is a lambda function that takes a list x and sorts each sublist within it using the sorted() function. It returns a generator of sorted sublists.
  • sec_Lar is another lambda function that takes a list x and a lambda function f. It applies the lambda function f to x, which sorts each sublist. Then, it extracts the second-to-last element (second-largest) from each sorted sublist using list comprehension and returns a list of second-largest elements.
  • The sec_Lar lambda function is called with the input list L and the sort_L lambda function as arguments. This means that it sorts each sublist in L and extracts the second largest element from each sorted sublist.
  • Finally, the result contains the list of second largest elements, and it is printed.

Using lambda() Function with filter() in Python

Code:

l = [15, 17, 20, 90, 44, 52, 70, 29, 63, 81]

final_l = list(filter(lambda x: (x % 2 != 0), l))
print(final_l)

Explanation:

  • The filter() function is used to filter elements from the list l based on a condition specified by the lambda function.
  • The lambda function lambda x: (x % 2 != 0) takes an element x as input and returns True if x is odd (i.e., not divisible by 2) and False otherwise.
  • filter(lambda x: (x % 2 != 0), l) applies the lambda function to each element in the list l. It selects and retains only those elements for which the lambda function returns True.
  • The final_l list is created using list(), which converts the filtered result into a list.
  • Finally, final_l is printed, containing only the odd numbers from the original list l.

Using lambda() Function With map()

Code:

l = [50, 70, 23, 94, 57, 32, 79, 13, 83, 61]

final_l = list(map(lambda x: x*2, l))
print(final_l)

Explanation:

  • The map() function is used to apply a specified function (in this case, a lambda function) to each element in the list l.
  • The lambda function lambda x: x * 2 takes an element x as input and returns x * 2, which effectively multiplies the element by 2.
  • map(lambda x: x * 2, l) applies the lambda function to each element in the list l. It returns an iterable containing the results of multiplying each element by 2.
  • The final_l list is created using list(), which converts the iterable returned by map() into a list.
  • Finally, final_l is printed, containing each element from the original list l multiplied by 2.

Using lambda() Function With reduce()

Code:

from functools import reduce
l = [15, 28, 12, 22, 53, 100]
sum = reduce((lambda x, y: x + y), l)
print(sum)

Explanation:

  • You import the reduce function from the functools module. The reduce() function is used to apply a binary function cumulatively to the items of an iterable, from left to right.
  • You have a list l containing integers.
  • You use the reduce() function to calculate the sum of the elements in the list. The reduce() function takes two arguments:
  • The first argument is a binary function (in this case, a lambda function) that takes two elements, x and y, and returns their sum (x + y).
  • The second argument is the iterable to which the binary function is applied (in this case, the list l).
  • The result of the reduce() function is stored in the sum_result variable.
  • Finally, you print the sum_result, which represents the sum of all elements in the list l.

Conclusion

Navigating through the world of lambda and anonymous functions in Python, we discern their potential to elevate code readability. As we stride forward in the dynamic realm of technology, the art of writing clear, concise code becomes more vital than ever. Enhance your coding prowess further, and stay ahead of the curve by exploring extensive upskilling opportunities on upGrad.

FAQS

1. What is lambda function in Python with example?

A lambda function is a concise, unnamed function. Example: multiply = lambda x, y: x*y.

2. How does a lambda function in Python list operate?

Lambda functions, when paired with functions like map() or filter(), can operate on each element of a list.

3. Is Python multiline lambda feasible?

While lambda is intended for single expressions, workarounds like using parentheses can simulate multiline behavior.

4. How does lambda for loop Python work?

Direct usage of for loops inside a lambda isn’t standard. However, lambdas can process lists resulting from loops.

5. What’s the main difference between Python lambda vs function?

Lambda offers brevity for small operations, especially where the function’s usage is temporary or limited.

Ready to challenge yourself? Take our Free Python Quiz!

image
right-top-arrowright-top-arrow
Need More Help? Talk to an Expert
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. .