[Tutor] Sorting tuples

Steven D'Aprano steve at pearwood.info
Thu Jun 21 02:15:13 CEST 2012


Mike Nickey wrote:
> While i'm still not sure what lamda is or represents, I've found a solution.

Unfortunately, you haven't. It's only by accident that your not-quite-solution 
gives the correct value for the example data.

Try it with this data instead:

[(1, 7), (1, 3), (3, 4, 8), (2, 2)]

required result: [(2, 2), (1, 3), (3, 4, 8), (1, 7)]
your result: [(2, 2), (1, 3), (1, 7), (3, 4, 8)]

> This seems to work:
> def sort_last(tuples):
>     return sorted(tuples, key=myDef)


You have the right idea: sort the list of tuples, using a custom key function. 
But you have misunderstood the question. Earlier you said:

"What is being asked is to sort tuples based on the SECOND element of the 
tuple in ascending order." [emphasis added]

not the last element.

Remember that elements are numbered from 0, so the first element of a tuple 
has index 0, the second element has index 1, the third index 2, and so forth; 
also you can index from the end: the last element is -1, the second element is 
-2, and so forth.

You also asked what "lamda" is. Nothing -- it doesn't exist. However lambda 
(note the spelling) does exist, and it is a Python short-cut for creating an 
anonymous function.

(For the record, lambda is the Greek letter L. There is a field of computer 
science called "lambda calculus" which is very important to the theory of 
computing, and involves the deep fundamentals of functions and functional 
programming.)

The syntax is:

lambda arguments : expression

which is a short-cut for:

def func(arguments):
     return expression

except that no "func" variable is created (the anonymous part). An example 
might make this more clear:

lambda x, y=2: 3*x + y

creates an anonymous function object which takes one required argument x, and 
one optional argument y defaulting to 2, and returns the value of 3*x + y.

You should consider lambda to be entirely optional, and moderately advanced. 
Using lambda is never *necessary*, but sometimes it is convenient.



-- 
Steven


More information about the Tutor mailing list