Tutorial Playlist
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.
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.
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:
Lambda functions offer distinct advantages:
The basic syntax of a lambda function is as follows:
lambda arguments: expression
In the above syntax,
Code:
# A lambda function that squares a number
square = lambda x: x**2
# Using the lambda function
result = square(4)
print(result) # Output: 16
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:
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.
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:
Example: lambda x, y: x + y
Functions defined with def:
Example: def add(x, y): return x + y
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.
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.
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.
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:
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:
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:
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:
Code:
from functools import reduce
l = [15, 28, 12, 22, 53, 100]
sum = reduce((lambda x, y: x + y), l)
print(sum)
Explanation:
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.
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.
PAVAN VADAPALLI
popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
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. .