-3

Today, I encounter a code slide below and I am confused that why key=takeSecond is a valid syntax. I mean, shouldn't it be key=takeSecond(elem)? However, the code works perfectly and I don't know why.

# take second element for sort
def takeSecond(elem):
    return elem[1]

# random list
random = [(2, 2), (3, 4), (4, 1), (1, 3)]

# sort list with key
random.sort(key=takeSecond)

# print list
print('Sorted list:', random)
Zephyr
  • 11,891
  • 53
  • 45
  • 80
XuZhan
  • 1
  • 1
    key takes random as parameter . You should go through object Oriented concepts to understand this. – Bimarsha Khanal Jul 11 '20 at 09:28
  • I'd suggest reading https://docs.python.org/3/howto/sorting.html - the key needs to be *callable*, with a single argument. – jonrsharpe Jul 11 '20 at 09:31
  • No. The key point you are missing is that in Python functions are just like any other object. The can be assigned to a name, `myfunc = takeSecond` and they can be passed as arguments to a function, or returned from a function. Just like `int`,`list`, or what have you. IOW Python has first-class functions – juanpa.arrivillaga Jul 11 '20 at 09:46

5 Answers5

1

The sort method takes as key parameter the function, you're asking why right?. So, it's taking a function because if you'll do takeSecond(elem) then Python just return the value.

If you implement it in this way:

random.sort(key=takeSecond((1, 2)))

It's equal to this:

random.sort(key=2) # Because the function returns 2 (elem[1]).

And it's incorrect. So you provide to sort method the function that he can call it, I'll show you a function that takes another function as argument for better understanding.

Here it is:

def get_func(function, values):
    for item in values:
        function(item) # For every item in the list it'll execute this function.

So the function receives the function and uses it, equals to how sort method uses it.

Tom Danilov
  • 307
  • 3
  • 18
1

takeSecond(elem) means you're calling the function takeSecond with elem as a paramter and getting the results back. However if you pass just the function name such as key=takeSecond you're passing the function object which can be called by the sort function.

Here is an in-depth explanation

orestisf
  • 1,396
  • 1
  • 15
  • 30
FluidLight
  • 446
  • 3
  • 10
  • Thank you. BTW, when the code run to 'random.sort(key=takeSecond)',and the takesecond() is invoked. How can the interpreter know which argument should be passed to takesecond()? Or the method sort() take the elements of the list 'random' as arguments by default? – XuZhan Jul 12 '20 at 12:14
0

With the key argument you specify the function that will be called with each element of the list being sorted. Specifying such a function is useful when the list's elements are structured as in your case and you want to sort based on a certain component of that structure.

If you were to specify key=taksecond(elem), takesecond(elem) is an immediate call to your function with argument elem (which happens to be undefined; it is only defined in the function takesecond when the passed argument is bound to the name elem) and that surely would only be correct if the returned value from that call happened to be a function to be used for comparing the keys.

Booboo
  • 38,656
  • 3
  • 37
  • 60
  • Thank you very much. Can you explain 'it is only defined in the function takesecond when the passed argument is bound to the name elem' futher? I don't quite catch that. – XuZhan Jul 12 '20 at 12:06
  • If you tried to sort with `random.sort(key=takeSecond(elem)`, you would get an error because `elem` is not defined at the point *where you are calling `takeSecond`*. `elem` is, however, defined *in* function `takeSecond`: it is the name of the formal argument being passed to that function. – Booboo Jul 12 '20 at 12:29
0

The key parameter of list.sort() can take in function which returns a value. It compares these values against each other to sort the content

def takeSecond(elem):
   return elem[1]

Each parameter of the list will be passed into the takeSecond() function, something like this

 # takeSecond((2, 2)),   #first  return 2
 # takeSecond((3, 4)),   #second return 4
 # takeSecond((4, 1)),   #third  return 1
 # takeSecond((1, 3)).   #fouth  return 3

so the sort function is comparing 2, 4, 1, 3 which be be used to position the resulting element in the list

-2

For list, python has the method list.sort(key=None, reverse=False), that sort list by which key

You can check here

Mughees
  • 832
  • 7
  • 16
mickeyandkaka
  • 1,452
  • 2
  • 11
  • 21