
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Why Python Lambda Expressions Can't Contain Statements
Yes, Python Lambda Expressions cannot contain statements. Before deep diving the reason, let us understand what is a Lambda, its expressions, and statements.
The Lambda expressions allow defining anonymous functions. A lambda function is an anonymous function i.e. a function without a name. Let us see the syntax ?
lambda arguments: expressions
The keyword lambda defines a lambda function. A lambda expression contains one or more arguments, but it can have only one expression.
Lambda Example
Let us see an example ?
myStr = "Thisisit!" (lambda myStr : print(myStr))(myStr)
Output
Thisisit!
Sort a List by values from another list using Lambda
In this example, we will sort a list by values from another list i.e. the 2nd list will have the index in the order in which they are placed in sorted order ?
# Two Lists list1 = ['BMW', 'Toyota', 'Audi', 'Tesla', 'Hyundai'] list2 = [2, 5, 1, 4, 3] print("List1 = \n",list1) print("List2 (indexes) = \n",list2) # Sorting the List1 based on List2 res = [val for (_, val) in sorted(zip(list2, list1), key=lambda x: x[0])] print("\nSorted List = ",res)
Output
List1 = ['BMW', 'Toyota', 'Audi', 'Tesla', 'Hyundai'] List2 (indexes) = [2, 5, 1, 4, 3] Sorted List = ['Audi', 'BMW', 'Hyundai', 'Tesla', 'Toyota']
Lambda Expressions cannot contain statements
We have seen two examples above wherein we have used Lambda expressions. Python lambda expressions cannot contain statements because Python's syntactic framework can't handle statements nested inside expressions.
Functions are already first-class objects in Python, and can be declared in a local scope. Therefore, the only advantage of using a lambda instead of a locally defined function is that you don't need to invent a name for the function i.e. anonymous, but that's just a local variable to which the function object is assigned!