For working professionals
For fresh graduates
More
13. Print In Python
15. Python for Loop
19. Break in Python
23. Float in Python
25. List in Python
27. Tuples in Python
29. Set in Python
53. Python Modules
57. Python Packages
59. Class in Python
61. Object in Python
73. JSON Python
79. Python Threading
84. Map in Python
85. Filter in Python
86. Eval in Python
96. Sort in Python
101. Datetime Python
103. 2D Array in Python
104. Abs in Python
105. Advantages of Python
107. Append in Python
110. Assert in Python
113. Bool in Python
115. chr in Python
118. Count in python
119. Counter in Python
121. Datetime in Python
122. Extend in Python
123. F-string in Python
125. Format in Python
131. Index in Python
132. Interface in Python
134. Isalpha in Python
136. Iterator in Python
137. Join in Python
140. Literals in Python
141. Matplotlib
144. Modulus in Python
147. OpenCV Python
149. ord in Python
150. Palindrome in Python
151. Pass in Python
156. Python Arrays
158. Python Frameworks
160. Python IDE
164. Python PIP
165. Python Seaborn
166. Python Slicing
168. Queue in Python
169. Replace in Python
173. Stack in Python
174. scikit-learn
175. Selenium with Python
176. Self in Python
177. Sleep in Python
179. Split in Python
184. Strip in Python
185. Subprocess in Python
186. Substring in Python
195. What is Pygame
197. XOR in Python
198. Yield in Python
199. Zip in Python
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.
Take our Free Quiz on Python
Answer quick questions and assess your Python knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.