[Tutor] sorted question

Steven D'Aprano steve at pearwood.info
Wed Jan 26 05:55:51 CET 2011


It't me wrote:
> 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

Why is the function called "sort" when it doesn't sort?

Why not call it "run" or "cook" or "pink" or "xhg6gf2jgf"?

Function names *must* tell you what they do, or at least give you a 
hint. Misleading names like "sort" for something that doesn't sort is 
very bad. Even a name like "xhg6gf2jgf" would be better than a name that 
lies about what it does.


> 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.

Do you mean the sort function you wrote, or the built-in list sort 
method? I'll assume you mean the sort function you wrote.


> But where comes the var value from?
> Does sort automatic pass the value from tup to (var)

No. sorted() passes the values to the key function "sort". "sort" 
*receives* those values, it doesn't go and get them.

When you write a function with an argument, the argument isn't defined 
until you call it:


def add_one(x):
     return x + 1


x is a local variable of the function, but is not yet defined. But when 
you call the function:

add_one(42)

x is set to 42.


In your "sort" function, the local variable is called "var". Calling

sorted(tup, key=sort)

with tup = [(1, 3), (3, 2), (2, 1)] results in the sorted() function 
calling your key function "sort" with each of the items in turn:

* build a new list by calling the "sort" function with (1,3), then 
(3,2), then (2, 1)

* sort a copy of the original list according to the values in the new list

* return the sorted copy



-- 
Steven


More information about the Tutor mailing list