Search code examples
pythonfunctionpython-3.xsortinglambda

Explain basic lambda function and sort


I have just finished my code for a school project, but have used one line of code from stack overflow that is slightly more advanced than the knowledge that's in my "skill comfort zone". I do understand what it does, why it exists, etc.. But still cannot convert it into "human syntax" for my individual report. Could anyone give me a bit of their time and explain, as precisely as possible, the underlying mechanism in this line of code? Thanks in advance!

sites.sort(key = lambda x: x[0]) 

The role it has within my program is sorting a dictionary by the integers in its first column, from smallest to biggest.

Need to demonstrate that I fully understand this line of code, which I frankly do not.

Thanks!


Solution

  • When calling sort on an object, Python passes each of the elements contained inside that object to the function you specify as the key parameter.

    A lambda function can be dissected in the following parts:

    lambda <args>: <what to do with args>
    

    In your lambda function you have a single arg x as the <args>, and your <what to do with args> is to get the zero element of it.

    That element x[0] is going to be used in the comparisons sort performs.

    In your example, sites must contain elements that themselves contain elements, for example, nested lists: l = [[1, 2, 3], [0, 1, 2, 3]]. Using this example, Python is first going to pass [1, 2, 3] to the lambda as the value of x and the lambda function is going to return x[0] == 1, then it will pass [0, 1, 2, 3] to it and get back x[0] == 0. These values are used during sorting to get the ordering as you require.