0

How could I convert the following line of code using a lambda command into a function by itself?

I am struggling to get the hang of lambda, and wanted to apply it to an example I found. I am confused about how to convert the x and y when I put it in it's own function, like def sortedList(myList)

The line with the lambda is as follows:

myList = [[1,2],[19,20],[2,3]]    
listNums = sorted(myList, 
                      sortList = lambda x,y: x[0] + y[0] if x[0] == y[0] else y[1] - x[1])
1
  • 3
    The equivalent code without a lambda would be raise TypeError("'sortList' is an invalid keyword argument for this function") Commented Nov 11, 2016 at 16:04

1 Answer 1

1
listNums = sorted(myList, 
                  sortList = lambda x,y: x[0] + y[0] if x[0] == y[0] else y[1] - x[1])

is equivalent to

def funcname(x,y):
    return x[0] + y[0] if x[0] == y[0] else y[1] - x[1]

listNums = sorted(myList, sortList=funcname)

However, that is not the correct syntax for sorted - it should be

listNums = sorted(mylist, cmp=funcname)

To address your comment, sorted uses the cmp function to sort the elements of your list. In your question, your list is [[1,2],[19,20],[2,3]]. The basic question is, which comes first [1,2] or [19,20]? Because that question could be answered nearly infinite different ways, it lets you provide the answer with a cmp function. In that case, to decide which of those pairs comes first, sorted will run cmp(x=[1,2], y=[19,20]). If the value is > 0, it assumes x is higher, if it is < 0 it considers y as higher, and if the return value is 0 it figures they are the same value.

The example you chose seems a weird way to do comparisons... if the first values are equal, return the sum of the first values? If they are both positive, then x will always be higher, if they are both negative, y will always be higher. If they aren't equal, sort solely based on the second value.

Sign up to request clarification or add additional context in comments.

2 Comments

More nuance required: you can't just replace the one with the other. For one thing, a lambda can only contain a single expression, which is returned with a return statement
Hi Paul. Thanks for the response. I understand what you wrote in your answer. But I am stumped on how to convert this example into a function. For example, my list has three pairs. But the sortList function is only addressing x[0] and y[0].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.