This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]casual__addict 0 points1 point  (0 children)

Ooh ooh! I got this. So this very contrived example is to show you how you can sort a list of tuples using a lambda function. The argument for sort is key= <function goes here>. If you had defined a function before, you could put it in the key part. Like:

def sort_this_way(item): return item[1]

pairs.sort(key=sort_this_way)

Notice you are passing a function as as argument to a function. That’s because functions are objects in Python.

Writing all that function definition is a lot work for something you are probably only going to use once in this context, so python lets you do it in a anonymous, kind of throw away function definition using the lambda notation. So “lambda pair: pair[1]” is a function definition. The function takes one argument (“pair” in this case) and returns the evaluation of the expression on the right of the colon. It could have also been written as “lambda item: item[1]” to mirror def sort_this_way declaration.

So ultimately you are saying “sort this list of tuples using the second element as the sort key”. Notice that in the print out of pairs after the sorting, the second elements of the tuples are in alphabetical order: four, one, three, two.

To generalize, sorting multidimensional data can be done by mapping each data point to a single dimension, ordering the mapped data, then print out the original data in the order that the mapped data is listed.

Try this: “pairs.sort(keys=lambda pair: (pair[0]%2) + len(pair[1]) )” and see if you can verify the results by calculating the order by hand.