[Tutor] sorted question

Emile van Sebille emile at fenx.com
Wed Jan 26 01:53:07 CET 2011


On 1/25/2011 11:46 AM It't me said...
> Hi all,
>
> I'm learning Python with Google's Python class
>
> Ik have a question about the following code:
> =================================
> def sort(var):
>   return var[-1]  #returns the last character of var

Nit: it'll be a character if passed in a string of characters.  If you 
pass in a tuple or list, it'll be the last thing in the list.

>
> def sort_last():
>    tup = [(1, 3), (3, 2), (2, 1)]
>    print(sorted(tup, key=sort))
>
> sort_last()
> ==================================
>
> I uderstand everything except (var) value.
> I understand that key=sort calls the sort function.
> But where comes the var value from?
> Does sort automatic pass the value from tup to (var)
>
> because (var) is nowhere defined.

in the line

     def sort(var):

var becomes in effect a placeholder for whatever value is passed to the 
function.

in the line

     print(sorted(tup, key=sort))

sort is being passed into sorted, and looking into the python 
documentation for sorted we find two things.



sorted(iterable[, cmp[, key[, reverse]]])¶

     Return a new sorted list from the items in iterable.



1) that sorted expects the first paramater to be iterable.  And a bit 
further we find...



     key specifies a function of one argument that is used to extract a 
comparison key from each list element: key=str.lower. The default value 
is None (compare the elements directly).


Aahh... there it is  -- each element of the iterable will be passed into 
the function named by key to determine the comparison key.


Now, applies to your code this means that for each pair in
    [(1, 3), (3, 2), (2, 1)] sorted will comare the result of your sort 
function when passed that pair, and your sort function returns the last 
element in that pair.


HTH,

Emile



More information about the Tutor mailing list