Reputation: 47
Sorry I can't understand what happens when key = key:
def key(x):
return x[1]
a = [(1, 2), (3, 1), (5, 10), (11, -3)]
a.sort(key=key)
Upvotes: 0
Views: 62
Reputation: 735
The sort function, as chaooder says, needs a named parameter, which is "key". This is the parameter for the funtion, and it is always named "key".
When you call the function, you pass another function as the value for this parameter. You can set whatever name you want for this function.
The thing that is confusing you is that in your code the function you pass as value happens to have the same name as the parameter - "key".
I bet it would not confuse you as much if you have it like this:
def mykey(x):
return x[1]
a = [(1, 2), (3, 1), (5, 10), (11, -3)]
a.sort(key=mykey)
EDIT: user Talon answered the same while I was writing this one, so he beat me to it :)
Upvotes: 1
Reputation: 1506
You need to first understand what is a keyword (named) argument: https://treyhunner.com/2018/04/keyword-arguments-in-python/
Thereafter, you can see that for the sort
method that belongs to the "a
" list, you can see that it has a named argument of key
: https://www.programiz.com/python-programming/methods/list/sort
The named argument key
takes in a function in which the return value of that function will be used for sorting, which in your case, the key
function defined at line 1 will use the second element of each tuple in the list for sorting.
i.e.
key
on the LHS = named argument of sort
method belonging to a listkey
on the RHS = key
function defined that returns a value to be used for sorting the listUpvotes: 3
Reputation: 1884
sort
takes a keyword argument named key
. With a.sort(key=key)
, the function key
is given for the keyword argument key
. The sort function then applied the key
function to every element in the list and then sorts the list by the result of this function call.
This may get less confusing when you rename the function, e.g. key_function.
def key_function(x):
return x[1]
a = [(1, 2), (3, 1), (5, 10), (11, -3)]
a.sort(key=key_function)
The function returns the second element of the input value, so the value for (1, 2)
will be 2
and for (3, 1)
it will be 1
. These values will then determine how the tuples will be ordered other than how tuples will usually be sorted.
Upvotes: 1