Home >Backend Development >Python Tutorial >Why can't Python's lambda expressions contain statements?
Yes, Python Lambda expressions cannot contain statements. Before we delve into the reasons, let’s understand what Lambda is, its expressions and statements.
Lambda expressions allow the definition of anonymous functions. A Lambda function is an anonymous function without a name. Let’s look at the syntax −
lambda arguments: expressions
The keyword lambda defines a lambda function. A lambda expression contains one or more parameters, but it can only have one expression.
Let’s look at an example −
myStr = "Thisisit!" (lambda myStr : print(myStr))(myStr)
Thisisit!
In this example, we will sort the list based on the values of another list, i.e. the second list will be sorted by their index in the 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)
List1 = ['BMW', 'Toyota', 'Audi', 'Tesla', 'Hyundai'] List2 (indexes) = [2, 5, 1, 4, 3] Sorted List = ['Audi', 'BMW', 'Hyundai', 'Tesla', 'Toyota']
We saw two examples of using Lambda expressions above. Python's Lambda expressions cannot contain statements because Python's syntax framework cannot handle statements nested within expressions.
In Python, functions are already first-class objects and can be declared in local scope. So the only advantage of using a lambda instead of defining the function locally is that you don't need to give the function a name, i.e. an anonymous function, but it's just a local variable that is assigned to the function object!
The above is the detailed content of Why can't Python's lambda expressions contain statements?. For more information, please follow other related articles on the PHP Chinese website!