0

Consider the following code snippet.

    ## Heading ##
    def pos(l):
        count_positive=0
        for i in l:
            if i>0:
                count_positive+=1
        return count_positive
    def even(l):
        count_even=0
        for i in l:
            if i%2==0:
                count_even+=1
        return count_even
    list_int=[[2,-3,-6,10],[10,34,26,87],[1,-2,-3,4]]
    list_int=sorted(list_int,key=lambda x: (pos(x),even(x)))
    print(list_int)

Lambda functions can't have more than one expression.

But in the code above, I am trying to sort the 2D list first based on number of positive elements and then based on number of even elements. Doesn't this mean that there are two expressions in the lambda function? Or is it like, as I have enclosed the two conditions inside a tuple, it would be considered as one single condition?

Mithra
  • 19
  • 5

2 Answers2

0

You have one expression - a tuple that calls two functions to get its values. A single "expression" can call multiple functions.

What "Lambda functions can't have more than one expression" means if that you can't have multiple "lines of code" within a lambda, meaning you can't do something like:

lambda x: print(x) return x+1
D Stanley
  • 149,601
  • 11
  • 178
  • 240
0

Doesn't this mean that there are two expressions in the lambda function?

Yes, there's two expressions, but there's only one expression being returned. When you do

lambda x: (pos(x), even(x))

you're creating a lambda that returns a single value: a tuple with two elements. You can see this by doing

f = lambda x: (pos(x), even(x))
print(f([1, 2, 3, 4]))        # Outputs (4, 2)
print(f([-1, -2, -3, -4]))    # Outputs (0, 2)

Since it returns a tuple, when you use this as your sorted key, it compares using tuple comparison.

About lambdas, Python documentation says

[Lambdas] are syntactically restricted to a single expression.

It means that you can't do

f = lambda x: pos(x), even(x)
# It'll be parsed as f = ((lambda x: pos(x)), (even(x)))

f = lambda x: return pos(x); return even(x)
# It'll throw a SyntaxError

Or is it like, as I have enclosed the two conditions inside a tuple, it would be considered as one single condition?

No, because this doesn't make sense. A single condition would only be considered if you connect them explicitely with a operator, such as addition:

f = lambda x: pos(x) + even(x)
# Sorts the lists based on the sum of the count of the positive
# numbers with the count of the even numbers
enzo
  • 9,861
  • 3
  • 15
  • 38