This calling the sorted()
function that will sort the elements of the sub
list that you know which is. What you probably do not know is the argument calling key
.
If you do not know this is a named argument, which is different from the arguments we normally use that is identified by the position it is used, so it would be the first argument played in the variable of the first parameter of the called function, and the second one goes to the second parameter, and so on. This does not matter what position you are on, you say his name, but the great advantage is that he better documents what he is doing, in this case he is indicating how the classification key should be composed.
Here comes the other thing you might not know is that the lambda . It is a way to define a very simple algorithm, more or less as you do in a function, but it will not run as normally occurs with normal functions. You are passing the algorithm as an argument, who will perform this algorithm is the internal part of the sorted()
function. Then there the classification will occur according to the result of the size()
function, in each element of the sub
list there will be an interaction and during the classification the element of that interaction will be passed as argument to the lambda so this value will be received in x
and this will be used as argument in function size()
.
As far as I understand, the function size()
takes up how many connected bits it has in the last number, until it finds the first 0. The algorithm has an unused variable, something that says it does not do what is expected.
Lambda is a way for you to slow down the execution of an algorithm that needs to be defined at that time.
If you want to understand more about lambda , you can read another answer in another language , but the concept is the same, and has links there for other answers that help you understand. I did not want to get into the details of the inner workings of a lambda , but in essence it is an unnamed function of just one line (it can not have a complex algorithm) and a reference to this code is is passed as an argument and then executed where it needs at the right time.
You can see how it is used internally (this is a very simplified sort function only to illumine the use of lambda ):
def sorting(list, key):
for i in range(len(list)):
for j in range(i, len(list)):
if key(list[i]) > key(list[j]): #a lambda sendo chamada aqui
list[i], list[j] = list[j], list[i]
def size(int_type):
length = 0
count = 0
while (int_type):
count += (int_type & 1)
length += 1
int_type >>= 1
return count
arr = [5,4,3,1,6,8,10,9]
sorting(arr, lambda x : size(x))
print(arr)
See running on ideone . And no Coding Ground . Also put it in GitHub for future reference .